
--BEFORE CODE 08.02.2016
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_OPTIONS_SGU_DOP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_OPTIONS_SGU_DOP', 'Выгружать ЭКР в поле Доп.Класиификации', 27, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_OPTIONS_SGU_DOP', NAME = 'Выгружать ЭКР в поле Доп.Класиификации', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_OPTIONS_SGU_DOP'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_SGU_DOP', 'TITLE', 'Выгружать ЭКР в поле Доп.Класиификации'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_SGU_DOP', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_SGU_DOP', 'CONTROLSOURCE', 'm.cALIAS+ ".SGU_DOP"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_SGU_DOP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_SGU_DOP', 'CONTROL_TYPE', ''
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_SGU_DOP', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_SGU_DOP', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_SGU_DOP', 'SHORT_CODE_OBJ', 'SGU_DOP'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_SGU_DOP', 'CONTROLSOURCE_EDIT', 'm.cALIAS+ ".SGU_DOP"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_SGU_DOP', 'CONTROL_NAME_EDIT', 'Pages.Page1.aChkSguDop'
GO
EXECUTE X_FORM_VIEW_OPTIONS 'BB_ZAYAVKA_KR_OPTIONS'
GO

GO
ALTER TABLE [dbo].[FINANSE_PAYS] ALTER COLUMN [BO_NUM] char(19) NOT NULL 
GO

GO
ALTER TABLE [dbo].[REPORT_DINAMICS] ALTER COLUMN [Code_Row] varchar(100) NOT NULL 
GO

GO

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


IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_LINK_SS_SFIN')
CREATE INDEX [IX_LINK_SS_SFIN] ON [dbo].[SAL_SFIN] ([LINK_SS_SFIN]) ON [INDEX]
GO

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

GO
IF COLUMNPROPERTY(object_id('[dbo].[SDOC_DGH_TABLE]'), 'LINK_VKR2', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SDOC_DGH_TABLE] ADD [LINK_VKR2] int NULL 
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SDOC_DGH_TABLE_SAL_SFIN2]'))
ALTER TABLE [dbo].[SDOC_DGH_TABLE] 
ADD CONSTRAINT [FK_SDOC_DGH_TABLE_SAL_SFIN2] FOREIGN KEY ([LINK_VKR2]) REFERENCES [dbo].[SAL_SFIN] ([LINK])
GO

ALTER TABLE [dbo].[SDOC_DGH_TABLE] DISABLE TRIGGER ALL

UPDATE A SET 
	A.[LINK_VKR2] = A.[LINK_VKR]
FROM
	[dbo].[SDOC_DGH_TABLE] A
	INNER JOIN dbo.PAYS P ON P.LINK = A.LINK_PAY
WHERE
	P.[OBJECT] = 3
	AND
	A.[LINK_VKR2] IS NULL	
	
ALTER TABLE [dbo].[SDOC_DGH_TABLE] ENABLE TRIGGER ALL
GO

	
GO

IF COLUMNPROPERTY(object_id('[dbo].[SDOC_DOT_TABLE]'), 'LINK_VKR2', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SDOC_DOT_TABLE] ADD [LINK_VKR2] int NULL 
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SDOC_DOT_TABLE_SAL_SFIN2]'))
ALTER TABLE [dbo].[SDOC_DOT_TABLE] 
ADD CONSTRAINT [FK_SDOC_DOT_TABLE_SAL_SFIN2] FOREIGN KEY ([LINK_VKR2]) REFERENCES [dbo].[SAL_SFIN] ([LINK])
GO

ALTER TABLE [dbo].[SDOC_DOT_TABLE] DISABLE TRIGGER ALL

UPDATE [dbo].[SDOC_DOT_TABLE] SET [LINK_VKR2] = [LINK_VKR] WHERE [LINK_VKR2] IS NULL

ALTER TABLE [dbo].[SDOC_DOT_TABLE] ENABLE TRIGGER ALL
GO

ALTER TABLE [dbo].[SDOC_DOT_TABLE] ALTER COLUMN [LINK_VKR2] int NOT NULL 
GO


GO

IF COLUMNPROPERTY(object_id('[dbo].[SDOC_ESN_TABLE]'), 'LINK_VKR2', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SDOC_ESN_TABLE] ADD [LINK_VKR2] int NULL 
GO

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

ALTER TABLE [dbo].[SDOC_ESN_TABLE] DISABLE TRIGGER ALL

UPDATE [dbo].[SDOC_ESN_TABLE] SET [LINK_VKR2] = [LINK_VKR] WHERE [LINK_VKR2] IS NULL

ALTER TABLE [dbo].[SDOC_ESN_TABLE] ENABLE TRIGGER ALL
GO

ALTER TABLE [dbo].[SDOC_ESN_TABLE] ALTER COLUMN [LINK_VKR2] int NOT NULL 
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
ALTER TABLE [dbo].[ZAYAVKA_KR_TABLE] ALTER COLUMN [LINK_SGU] int NULL 
GO
GO

--ОБЪЕКТЫ БД 08.02.2016
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
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.[DOCUMENTS_DED_OTHER_TABLE]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[DOCUMENTS_DED_OTHER_TABLE]

GO

CREATE VIEW dbo.DOCUMENTS_DED_OTHER_TABLE
AS

SELECT
	[LINK]		= SD.LINK_UP,
	[ORDERS]	= SD.ORDERS,
	[CODE_DED]	= P.CODE,
	[NAME_DED]	= P.[NAME],
	[REF_DED]	= SD.LINK_PAY,
	[LINK_VKR]	= SD.LINK_VKR,
	[NAME_VKR]	= F.CODE,
	[LINK_EKR]	= SD.LINK_EKR,
	[NAME_EKR]	= G.CODE,
	[SUMMA_BASE]	= SD.SUMMA_BASE,
	[PERCENT]	= SD.PERC,
	[SUMMA]		= SUM(SD.SUMMA),
	[SKIDKA] = SUM(ISNULL(S.SUMMA,0)),
	[VYCHET] = SUM(ISNULL(S2.SUMMA,0)),
	[LINK_VKR2]	= SD.LINK_VKR2,
	[NAME_VKR2]	= F2.CODE
FROM 	
	dbo.SDOC_DOT_TABLE SD 
	INNER JOIN dbo.PAYS P ON SD.LINK_PAY = P.LINK
	INNER JOIN dbo.SAL_SFIN	F ON F.LINK = SD.LINK_VKR
	INNER JOIN dbo.KOSGU G ON G.LINK = SD.LINK_EKR
	LEFT JOIN dbo.SAL_SFIN	F2 ON F2.LINK = SD.LINK_VKR2
	LEFT JOIN 
	(  	SELECT 
			LINK_UP, LINK_TAX, LINK_VKR, LINK_EKR, [PERCENT], SUMMA = SUM(SUMMA)
		FROM
			dbo.SDOC_DOT_SKIDKI
		GROUP BY
			LINK_UP, LINK_TAX, LINK_VKR, LINK_EKR, [PERCENT]	
	) S ON S.LINK_UP = SD.LINK_UP AND S.LINK_TAX = SD.LINK_PAY AND S.LINK_VKR = SD.LINK_VKR AND S.LINK_EKR = SD.LINK_EKR AND S.[PERCENT] = SD.PERC
	LEFT JOIN 
	(  	SELECT 
			LINK_UP, LINK_TAX, LINK_VKR, LINK_EKR, [PERCENT], SUMMA = SUM(SUMMA)
		FROM
			dbo.SDOC_DOT_VYCHET
		GROUP BY
			LINK_UP, LINK_TAX, LINK_VKR, LINK_EKR, [PERCENT]	
	) S2 ON S2.LINK_UP = SD.LINK_UP AND S2.LINK_TAX = SD.LINK_PAY AND S2.LINK_VKR = SD.LINK_VKR AND S.LINK_EKR = SD.LINK_EKR  AND S2.[PERCENT] = SD.PERC
GROUP BY
	SD.LINK_UP,
	SD.ORDERS,
	P.CODE,
	P.[NAME],
	SD.LINK_PAY,
	SD.LINK_VKR,
	F.CODE,
	SD.LINK_EKR,	
	G.CODE,	
	SD.SUMMA_BASE,
	SD.PERC,
	SD.LINK_VKR2,
	F2.CODE	

GO


GRANT SELECT ON dbo.[DOCUMENTS_DED_OTHER_TABLE] TO PUBLIC

GO

GO

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

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

CREATE             VIEW dbo.BB_ZAYAVKA_KR_TABLE
AS
Select	T.LINK, 
		T.LINK_UP, 
		KBK_LINK	= KBK.LINK,
		KBK_CODE	= KBK.CODE,
		KBK_NAME	= KBK.NAME,
		KBK_TYPE	= KBK.TYPE,
		KBK_LINK_D  = KBKD.LINK,
		KBK_CODE_D  = KBKD.CODE,
		KBK_NAME_D  = KBKD.NAME,
		KBK_TYPE_D	= KBKD.TYPE,
		SGU_LINK	= SGU.LINK,
		SGU_CODE	= SGU.CODE,
		SGU_NAME	= SGU.NAME,
		SGU_LINK_D  = SGUD.LINK,
		SGU_CODE_D  = SGUD.CODE,
		SGU_NAME_D  = SGUD.NAME,
		DCL_LINK	= DCL.LINK,
		DCL_CODE	= DCL.CODE,
		DCL_NAME	= DCL.NAME,
		DCL_LINK_D  = DCLD.LINK,
		DCL_CODE_D  = DCLD.CODE,
		DCL_NAME_D  = DCLD.NAME,
		DT_ACC_LINK = SA.LINK,
		DT_ACC_CODE = SA.CODE,
		BK_CODE	    = case isnull(ZO.KBK_DEL,0) when 0 then rtrim(KBK.Code) + '.' + SGU.Code + isnull('.' + DCL.Code,'') else replace(rtrim(KBK.Code) + SGU.Code + isnull(DCL.Code,''),'.','') end,
		BKD_CODE	    = case isnull(ZO.KBK_DEL,0) when 0 then rtrim(KBKD.Code) + '.' + SGUD.Code else replace(rtrim(KBKD.Code) + SGUD.Code + isnull(DCLD.Code,''),'.','') end,
		T.SUMMA,
		T.TITLE,
		T.TARGET,
		FS_LINK 		= FS.LINK,
		FS_CODE 		= FS.CODE,
		FS_NAME 		= FS.NAME,
		VID_SR 			= V.LINK,
		VID_SR_NAME 	= V.NAME,
		VID_SR_SNAME 	= V.SNAME
	
	
from dbo.ZAYAVKA_KR_TABLE T 
inner join dbo.KL_KBK KBK on KBK.LINK = T.LINK_KBK
inner join dbo.BB_ZAYAVKA_KR_SOURCE V on V.LINK = T.VYD_SR
inner JOIN dbo.BB_FIN_SOURCE FS ON FS.CODE = T.[SOURCE]
left join dbo.KOSGU  SGU on SGU.LINK = T.LINK_SGU
left join dbo.KL_KBK KBKD on KBKD.LINK = T.LINK_KBK_D
left join dbo.KOSGU  SGUD on SGUD.LINK = T.LINK_SGU_D
left join dbo.S_ACCOUNTS SA on SA.LINK = T.LINK_DT_ACC
left join dbo.DOP_CLASSIF DCL on DCL.LINK = T.LINK_DCL
left join dbo.DOP_CLASSIF DCLD on DCLD.LINK = T.LINK_DCL_D
left join dbo.BB_ZAYAVKA_KR_OPTIONS ZO on 1=1






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on dbo.BB_ZAYAVKA_KR_TABLE to public
GO

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

GO

CREATE FUNCTION [dbo].KJ_GET_AWARD_PERS_TABLE(@date datetime)
/*
	ФУНКЦИЯ ВОЗРАЩАЕТ ВСЕ НАГРАДЫ ФИЗИЧЕСКИХ ЛИЦ В ВИДЕ ТАБЛИЦЫ
*/

RETURNS @R TABLE (pers_link int, award_str varchar(1000))
AS
BEGIN
declare @str varchar(1000)
declare @tbl table (cod int, NAME VARCHAR (250), DATE DATETIME)
declare @i int
--
declare @pers_table table(link int identity(1,1), pers_link int)
insert @pers_table
select link from person
--
declare @pers_link int
declare @ind int
set @ind = 1
while	exists(select * from @pers_table where link = @ind) begin
	SET @STR = ''
	set @pers_link = (select pers_link from @pers_table where link = @ind)
	set @ind = @ind + 1


	insert into @tbl (cod, NAME, DATE)
	select LINK, LEFT(AWARD_NAME,250), DOC_DATE
	from KU_PERS_AWARD
	where pers_link = @pers_link and DOC_DATE <= @date

	set @str = ''
	while exists (select * from @tbl)
	begin
		select @i = min(cod) from @tbl
		(select @str = (case when len(@str + rtrim(NAME) + case when isnull(DATE,0) != 0 then '(' + convert(varchar(10),DATE,104)+ ')' else '' end  +
									  ', ') < 1000 then
		(@str + rtrim(NAME) + case when isnull(DATE,0) != 0 then '(' + convert(varchar(10),DATE,104)+ ')' else '' end  +
									  ', ') else @str end) from @tbl where cod = @i)
		delete from @tbl where cod = @i
	end
	declare @length int
	if len(@str)>2 set @length = len(@str)-1
	else set @length = 0
	set @str = left(@str,@length)		

	INSERT INTO @R
	VALUES(@pers_link, @str)
end
--
return
END



GO


GRANT SELECT ON dbo.[KJ_GET_AWARD_PERS_TABLE] TO PUBLIC

GO


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

GO

CREATE  VIEW dbo.DOCUMENTS_DGH_T3

AS
SELECT 	[LINK] = LINK_UP,
	ORDERS,
	PERS_LINK,
	[FIO] = rtrim(PER.fm)+' '+left(PER.im,1)+'.'+left(PER.ot,1)+'.',
	LINK_PAY,
	[CODE_PAY] = P.CODE,
	[NAME_PAY] = P.[NAME],
	BASE_YEAR,
	SUMMA_BASE,
	[PERCENT],
	SUMMA_YEAR,
	SUMMA_OLD,	
	SUMMA,
	link_vkr,
	[name_vkr]= F.CODE,
	[WAY_CALC]= P.WAY_CALC,
	T.link_ekr,
	[code_ekr]= ekr.CODE,
	LINK_DOG,
	link_vkr2 = link_vkr2,
	name_vkr2 = F2.CODE	
FROM 
	dbo.SDOC_DGH_TABLE  T 
	INNER JOIN dbo.person PER ON PER.LINK = T.PERS_LINK
	INNER join dbo.PAYS P on T.LINK_PAY = P.LINK
	left join dbo.SAL_SFIN F on T.LINK_VKR = F.LINK
	left join dbo.SAL_SFIN F2 on T.LINK_VKR2 = F2.LINK
	left join dbo.DICTIONARY_ITEM EKR on EKR.LINK = T.LINK_EKR
WHERE T.OBJECT = 3



GO


GRANT SELECT ON dbo.[DOCUMENTS_DGH_T3] TO PUBLIC

GO

GO

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

GO

CREATE view [dbo].SALARY_SRC_FIN
as
select SF.LINK, 
	SF.CODE,
	SF.[NAME], 
	SF.KBK as LINK_KBK, 
	KBK.[CODE] as CODE_KBK, 
	KBK.[NAME] as NAME_KBK, 
	SF.[SOURCE],
	NSOURCE = BB.CODE + '.' + BB.NAME,
	SF.ENVD,
	NENVD = CASE WHEN SF.ENVD = 1 THEN 'ЕНВД' else '' end,
	SF.USER_ACC,
	SF.KAU as LINK_KAU,
	KAU.[CODE] as CODE_KAU,
	KAU.[NAME] as NAME_KAU,
	SF.DOP_KL as LINK_DOP_KL,
	DOP.[CODE] as CODE_DOP_KL,
	DOP.[NAME] as NAME_DOP_KL,
	SF.COMMENT,
	SF.ACC_ESN,
	SF.LINK_LACC,
	CODE_LACC = DA.CODE, 
	NAME_LACC = DA.ANAME,
	USED = ISNULL(SF.USED,1),
	N_USED = case when SF.USED = 1 THEN 'Да' ELSE 'Нет' end,
	SF.LINK_CH_SFIN,
	NSF_CODE = NSF.CODE,
	NSF_NAME = NSF.NAME,
	SF.DATE_CHANGE,
	SF.LINK_SS_SFIN,
	SSF_CODE = SSF.CODE
from 
	dbo.SAL_SFIN SF 
	left join dbo.KL_KBK KBK on SF.KBK = KBK.LINK
	left join dbo.BB_FIN_SOURCE BB on BB.CODE = SF.[SOURCE] AND ISUSED = 1
	left join dbo.KAU KAU on SF.KAU = KAU.LINK
	left join dbo.DOP_CLASSIF DOP on SF.DOP_KL = DOP.LINK
	left join dbo.DICTIONARY_ACCOUNTS DA on SF.LINK_LACC = DA.LINK
	LEFT JOIN dbo.SAL_SFIN NSF ON NSF.LINK = SF.LINK_CH_SFIN
	LEFT JOIN dbo.SAL_SFIN SSF ON SSF.LINK = SF.LINK_SS_SFIN
GO

GRANT SELECT ON dbo.[SALARY_SRC_FIN] 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].[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_NAME,STA.BANK_NAME)), 
		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_NAME,DTA.BANK_NAME)), 
		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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

CREATE                   VIEW dbo.DOCUMENTS_RECEPTION_CASH
AS
SELECT  G.LINK,
		  G.NUMBER,
		  SUMMA = ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA),
		  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,
		  DEP_B_CODE	= D.BUDG,
		  DEP_UBP	= D.CODE_UBP,
		  DEP_TYPE	= D.BUH_TYPE,
		  ACC_LINK  = G.ACC,
		  ACC_CODE  = DA.CODE,   
		  BANK_NAME = DA.ANAME,  
			
		  GRBS_NAME	= VED.NAME,
		  GRBS_CODE	= VED.CODE,
		  BUDG_NAME	= BUDG.NAME,
		  FO_NAME	= FO.FULL_NAME,
		  FO_CODE	= FO.CODE,
		  FO_OKPO	= FO.OKPO,
		  TOFK_NAME	= DA.KAZN_F_NAME,
		  TOFK_CODE	= DA.KAZN_CODE,
		  UCHR_NAME	= UCHR.NAME,

		  EMP_LINK	= GPEM.EMPL,
		  EMP_CODE	= EM.TAB, 
		  EMP_FM	= EM.FM, 
		  EMP_IM	= EM.IM, 
		  EMP_OT	= EM.OT, 
		  EMP_FIO	= EM.FIO, 
		  EMP_NAME	= EM.NAME_EMPL, 
		  EMP_POST	= EM.POST_NAME, 
		  ED_NUM	= PERS.DOC_NUM, 
		  ED_WHOM	= PERS.DOC_WHOM, 
		  ED_DOC	= isnull(FD.NAME,''),
		  ED_DATE	= PERS.DOC_DATE,
		  
		  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='RECEPTION_CASH_PKO')  AND GR.LINK = GPR.DOC_REF_FOREIGN),
		  
		  DATE_POD = CONVERT(DATETIME, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_DATE_POD')), 104),
		  
		  CHEK_SER = CONVERT(VARCHAR (2), (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_CHEK_SERIA'))),
		  CHEK_NO = CONVERT(VARCHAR (15), (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_CHEK_NO'))),
		  CHEK_DATE = CONVERT(DATETIME, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_CHEK_DATE')), 104),
		  CHEK_SROK = CONVERT(DATETIME, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_CHEK_SROK')), 104),

		  SROK = CONVERT(DATETIME, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_SROK')), 104),
		  PLAT_ORDER = CONVERT(VARCHAR(1), (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_ORDER'))),
		  REASON = CONVERT(VARCHAR(210), (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_REASON'))),
		  KIND = CONVERT(VARCHAR(50), (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_KIND'))),
		  UKAZ =  CONVERT(VARCHAR(254),  (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_UKAZ'))),
		  KP =  CONVERT(VARCHAR(2),  (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_KP'))),
		  NUM_BO =  CONVERT(VARCHAR(19), (SELECT GPV.VALUE FROM dbo.G_PROV_VALUE GPV WHERE GPV.DOC_LINK=G.LINK AND GPV.OBJECT=(SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'RECEPTION_CASH_NUM_BO'))),

		  DATE_NA = CONVERT(DATETIME, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_DATE_NA')), 104)
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_EMPL GPEM WITH (NOLOCK) on GPEM.DOC_LINK = G.LINK AND GPEM.OBJECT = (select link from s_objects where code='RECEPTION_CASH_EMP_LINK')
left join KU_EMPL_PLACING EM WITH (NOLOCK) on GPEM.EMPL = EM.LINK
left join PERSON PERS ON (PERS.LINK = EM.PERS_LINK)
left join dbo.FACE_DOCUMENT FD on FD.LINK = PERS.DOC_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
left join dbo.DEPARTMENTS DD WITH (NOLOCK) on DA.REF_LINK_D = DD.link
left join dbo.DEPARTMENTS UCHR WITH (NOLOCK) on D.UCHR_LINK = UCHR.LINK

WHERE G.OBJECT=(SELECT link from S_OBJECTS WHERE CODE='DOCUMENTS_RECEPTION_CASH')



GO
grant all on dbo.DOCUMENTS_RECEPTION_CASH to public

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

CREATE                   VIEW dbo.DOC_RECEPTION_CARD 
AS
SELECT  G.LINK,
		  G.NUMBER,
		  SUMMA = ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA),
		  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,
		  DEP_B_CODE	= D.BUDG,
		  DEP_UBP	= D.CODE_UBP,
		  DEP_TYPE	= D.BUH_TYPE,
		  DEP_INN  = D.INN,
		  DEP_KPP  = D.KPP,
		  ACC_LINK  = G.ACC,
		  ACC_CODE  = DA.CODE,   
		  BANK_NAME = DA.ANAME,  
		  VID_SR 		= VS.LINK,
		  VID_SR_NAME 	= VS.NAME,
		  VID_SR_SNAME 	= VS.SNAME,
		
		  TOFK_NAME	= DA.KAZN_F_NAME,
		  TOFK_CODE	= DA.KAZN_CODE,
		 
		  CARD_LINK	= PEC.LINK,
		  CARD_CODE	= PEC.LIC_SCHET, 
		  CARD_NAME	= B.NAME, 
		  EMP_LINK	= EM.LINK,
		  EMP_CODE	= EM.TAB, 
		  EMP_FIO	= EM.FIO, 
		  EMP_F		= EM.FM, 
		  EMP_I		= EM.IM, 
		  EMP_O		= EM.OT, 
		  EMP_NAME	= EM.NAME_EMPL, 
		  EMP_POST	= EM.POST_NAME, 
				  
		  DATE_POD = CONVERT(DATETIME, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CARD_DATE_POD')), 104),
		  
		  NUM_BO =  CONVERT(VARCHAR(19), (SELECT GPV.VALUE FROM dbo.G_PROV_VALUE GPV WHERE GPV.DOC_LINK=G.LINK AND GPV.OBJECT=(SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'RECEPTION_CARD_NUM_BO'))),

		  DATE_NA = CONVERT(DATETIME, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CARD_DATE_NA')), 104)

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_ECARD GPEC WITH (NOLOCK) on GPEC.DOC_LINK = G.LINK AND GPEC.OBJECT = (select link from s_objects where code='RECEPTION_CARD_CARD_LINK')
left join dbo.PERSON_ECARDS PEC on GPEC.ECARD = PEC.LINK
left join dbo.G_PROV_VALUE GPS WITH (NOLOCK) on GPS.DOC_LINK = G.LINK AND GPS.OBJECT = (select link from s_objects where code='RECEPTION_CARD_VID_SR_LINK')
LEFT JOIN dbo.BB_ZAYAVKA_KR_SOURCE VS ON VS.LINK = GPS.value
left join dbo.G_PROV_EMPL GPEM WITH (NOLOCK) on GPEM.DOC_LINK = G.LINK AND GPEM.OBJECT = (select link from s_objects where code='RECEPTION_CARD_EMP_LINK')
left join dbo.KU_EMPL_PLACING EM WITH (NOLOCK) on EM.LINK = GPEM.empl
left join dbo.BANKS B on B.LINK = PEC.BANK_LINK
 WHERE G.OBJECT=(SELECT link from S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD')




GO
grant all on dbo.DOC_RECEPTION_CARD to public

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO

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


GRANT SELECT ON dbo.[DOCUMENTS_ESN_G_TABLE] TO PUBLIC

GO

GO

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

GO

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

BEGIN

IF @date IS NULL
	SELECT @date = SC_DATE FROM dbo.SALARY_CALC_PERIOD

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

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

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

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

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

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

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

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

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

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

RETURN 

END





GO


GRANT SELECT ON dbo.[sa_dict_wh_pays_empl] TO PUBLIC

GO




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

GO



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

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

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

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

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

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

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


SET @intMAX_REC = 9

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

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

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

RETURN @varKSintResult




GO


GRANT EXECUTE ON dbo.[FB_REPORT] TO PUBLIC

GO


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

GO


CREATE       PROCEDURE [dbo].FB_SALDO_REPORT
	@varKSiFyear	int,
	@varKSdDate	datetime,
	@varKSiDocType	tinyint,
	@varKSiIFType	INT,
	@varKScVal1 char(1), 
	@varKSnOtborLink1 int,
	@varKScVal2 char(1) = '', 
	@varKSnOtborLink2 int,
	@varKScVal3 char(1) = '', 
	@varKSnOtborLink3 int


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

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


-- Выбираем счета из фильтра
DECLARE @DEP_ACC  TABLE (LINK_ACC [INT])	
IF LEN (@varKScVal1) > 0
	INSERT INTO @DEP_ACC
	SELECT RECORD
	FROM OBJECT_VAR_DEPARTMENT_ACCOUNTS
	WHERE LINK_UP = @varKSnOtborLink1
ELSE
	INSERT INTO @DEP_ACC
	SELECT LINK
	FROM dbo.DICTIONARY_DEP_ACCOUNTS_ZB

-- Выбираем КБК из фильтров по Подразделам и ЦС
DECLARE @varKStVKR  TABLE (LINK [INT])	
IF LEN (@varKScVal2) > 0 AND LEN (@varKScVal3) > 0
	INSERT INTO @varKStVKR
	SELECT LINK
	FROM dbo.KL_KBK KBK
	INNER JOIN dbo.KL_VKR VKR ON KBK.LINK = VKR.LINK_KBK 
	INNER JOIN dbo.OBJECT_VAR_DIVISION OVD ON OVD.LINK_UP = @varKSnOtborLink2 AND OVD.RECORD = VKR.LINK_DIV
	INNER JOIN dbo.OBJECT_VAR_TARGET_ITEM OVI ON OVI.LINK_UP = @varKSnOtborLink3 AND OVI.RECORD = VKR.LINK_CSR

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

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

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

SET @intMAX_REC = 9

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

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

IF @varKSFinObjCode like '%_ASSIGN%'
BEGIN
	SELECT @varKSintTypePer = max(FIN_SMETA_PER) FROM WorkMode
	SELECT @varKSintSummaType = ISNULL(UM,1) FROM FINANS_ASSIGN_OPTIONS
END
ELSE
BEGIN
	SELECT	@varKSintTypePer = max(FIN_LIM_PER) /* * 10 + max(FIN_LIM_PER))*/ FROM WorkMode
	SELECT @varKSintSummaType = ISNULL(UM,1) FROM FINANS_LIMIT_OPTIONS
END
INSERT INTO #TAB_TEMP (PER_NUM, PERIOD, VKR, EKR, DOP_CL, DEP_ACC, DEP_NAME, ACC_CODE, EKRCODE, VKR_CODE, VKR_NAME, DOP_CODE, SUMMA)
SELECT * FROM (SELECT P.ORD,(CASE @varKSintTypePer when 1 then 'год' else P.PERIOD end) as PERIOD, F.VKR, F.EKR, F.DOP_CL, F.DEP_ACC, 
	D.NAME  AS DEP_NAME, DA.CODE AS ACC_CODE,ISNULL(EKR.CODE,'000') AS EKRCODE, KBK.CODE AS VKR_CODE, KBK.NAME AS VKR_NAME, DCL.CODE AS DOP_CODE,
	[SUMMA] = (CASE P.ORD WHEN 1 THEN F.P1
			  WHEN 2 THEN F.P2
			  WHEN 3 THEN F.P3
			  WHEN 4 THEN F.P4
			  WHEN 5 THEN F.P5
			  WHEN 6 THEN F.P6
			  WHEN 7 THEN F.P7
			  WHEN 8 THEN F.P8
			  WHEN 9 THEN F.P9
			  WHEN 10 THEN F.P10
			  WHEN 11 THEN F.P11
			  WHEN 12 THEN F.P12
			  WHEN 13 THEN F.P1 + F.P2 + F.P3
			  WHEN 14 THEN F.P4 + F.P5 + F.P6
			  WHEN 15 THEN F.P7 + F.P8 + F.P9
			  WHEN 16 THEN F.P10 + F.P11 + F.P12
			  ELSE F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12 END)
FROM PERIODS P 
INNER JOIN (SELECT FS.VKR, FS.EKR, FS.DOP_CL, FS.DEP_ACC, 
	sum(FS.P1) as P1,
	sum(FS.P2) as P2,
	sum(FS.P3) as P3,
	sum(FS.P4) as P4,
	sum(FS.P5) as P5,
	sum(FS.P6) as P6,
	sum(FS.P7) as P7,
	sum(FS.P8) as P8,
	sum(FS.P9) as P9,
	sum(FS.P10) as P10,
	sum(FS.P11) as P11,
	sum(FS.P12) as P12,
	[ITOGS] = sum(FS.P1 + FS.P2 + FS.P3 + FS.P4 + FS.P5 + FS.P6 + FS.P7 + FS.P8 + FS.P9 + FS.P10 + FS.P11 + FS.P12)
	FROM dbo.FB_REST_SALDO_FINANS(@varKSiFyear, @varKSdDate, 0, @varKSintSummaType,0, @varKSFinObjCode, @varKSintTypePer, @varKScIF) FS
	WHERE FS.VKR IN (select LINK from @varKStVKR)
	GROUP BY FS.VKR, FS.EKR, FS.DOP_CL, FS.DEP_ACC) F ON F.EKR is not null --AND NOT SUMMA = 0
INNER JOIN DEPARTMENT_ACCOUNTS DA ON F.DEP_ACC = DA.LINK AND DA.LINK in (select LINK_ACC from @DEP_ACC)
LEFT JOIN DEPARTMENTS D ON DA.LINK_UP = D.LINK
LEFT JOIN KL_KBK KBK ON F.VKR = KBK.LINK
LEFT JOIN DICTIONARY_ITEM EKR ON F.EKR = EKR.LINK 
left outer JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = F.DOP_CL
WHERE 	(P.ORD < 13 AND @varKSintTypePer = 3) OR
	(P.ORD > 12 AND P.ORD < 17 AND @varKSintTypePer = 2) OR 
	(P.ORD = 20 AND @varKSintTypePer = 1)) FS WHERE NOT FS.SUMMA = 0 
ORDER BY FS.DEP_ACC,FS.ORD, FS.VKR, FS.EKR
--select * from #TAB_TEMP

IF @@ROWCOUNT =0
	SELECT * FROM #TAB_TEMP WHERE 1 > 2
ELSE
BEGIN
	create table #TAB_TEMP1(PER_NUM	int, 
				VKR	int, 
				DOP_CL	int, 
				DEP_ACC	int, 
				SUMMA	NUMERIC(19,2))
	insert into #TAB_TEMP1(PER_NUM, VKR, DOP_CL, DEP_ACC, SUMMA)
	select PER_NUM, VKR, DOP_CL, DEP_ACC, SUM(SUMMA)
	from #TAB_TEMP
	group by PER_NUM, VKR, DOP_CL, DEP_ACC    		
		
	-- Разворачиваем таблицу по ЭКР
	EXEC X_GET_TABLE_NAME @cCROSS_TABLE OUTPUT
	EXEC M_CROSS_TABLE 'PER_NUM, PERIOD, VKR, DOP_CL, DEP_ACC, DEP_NAME, ACC_CODE, VKR_CODE, VKR_NAME, DOP_CODE', 'EKRCODE', 'VARCHAR (60)', 'SUMMA', 'NUMERIC (28,4)', 'SUM (SUMMA) AS SUMMA', '#TAB_TEMP', @cCROSS_TABLE
	
	-- добавляем пустые столбцы до конца страницы
	SELECT @intCOUNTER = COUNT (DISTINCT EKR) FROM #TAB_TEMP 
		SET @intCOUNTER = ISNULL (@intCOUNTER, 0)
		SET @intCOUNT_COLROW = @intCOUNTER
		WHILE @intCOUNTER < @intMAX_REC
		BEGIN
			SET @intCOUNTER = @intCOUNTER + 1
			SET @cCOUNTER = LTRIM (STR (@intCOUNTER))
			SET @cSQL_STR = 'ALTER TABLE ' + @cCROSS_TABLE
				+ ' ADD EKRCODE_' + @cCOUNTER + ' VARCHAR (60) '
				+ ', SUMMA_' + @cCOUNTER + ' [NUMERIC] (28,4)'
			EXECUTE (@cSQL_STR)
		END 
	
		IF @intCOUNT_COLROW = 0
			EXEC ('INSERT INTO ' + @cCROSS_TABLE + ' (vkr_code) VALUES ('''') ')
	
	EXEC ('select T.*, TI.SUMMA as SUMMAI from ' + @cCROSS_TABLE + ' T
			left join #TAB_TEMP1 TI on T.PER_NUM = TI.PER_NUM and T.VKR = TI.VKR AND (T.DOP_CL = TI.DOP_CL or T.DOP_CL is null and TI.DOP_CL is null) AND T.DEP_ACC = TI.DEP_ACC
			ORDER BY T.DEP_ACC, T.PER_NUM, T.VKR_CODE,T.DOP_CODE')
		
		
	DROP TABLE #TAB_TEMP
	DROP TABLE #TAB_TEMP1
	EXEC ('DROP TABLE ' + @cCROSS_TABLE)
	
	select 	[um] 	= @varKSintSummaType, 
		[title]	= (case @varKSiDocType 	WHEN 1 	THEN  'ЛИМИТЫ БЮДЖЕТНЫХ ОБЯЗАТЕЛЬСТВ'
						WHEN 2 	THEN  'БЮДЖЕТНЫЕ АССИГНОВАНИЯ'
						WHEN 11 THEN  'СВОДНЫЕ ЛИМИТЫ БЮДЖЕТНЫХ ОБЯЗАТЕЛЬСТВ' 
						WHEN 12 THEN  'СВОДНЫЕ БЮДЖЕТНЫЕ АССИГНОВАНИЯ' END)  
	
END	
RETURN 1











GO


GRANT EXECUTE ON dbo.[FB_SALDO_REPORT] TO PUBLIC

GO




GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

CREATE           
PROCEDURE BB_EXPORT_ZN_16
	@cBuffId	varchar(30) = '',
	@cObjCode	varchar(30) = ''

AS
  DECLARE @iDepLink	int, @cCodeOpt int, @cExp2 int, @iLongFio tinyint, @iPostRuk tinyint, @iPostGl tinyint

set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())
set @cCodeOpt = dbo.sa_get_option_by_code('DOC_REC_CARD_OPTIONS_KODBP')
set @iLongFio = dbo.sa_get_option_by_code('DOC_REC_CARD_FIO')
set @iPostRuk = dbo.sa_get_option_by_code('DOC_REC_CARD_POST_RUK')
set @iPostGl = dbo.sa_get_option_by_code('DOC_REC_CARD_POST_GL_BUH')



-- Таблица 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	= D.FULL_NAME
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
from dbo.DEPARTMENTS D
inner join dbo.TREASURY TOFK on D.TOFK_LINK = TOFK.LINK
where D.LINK = @iDepLink



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

	SELECT  LINK 		 = ZS.LINK,
			LINK_UP		 = ZS.LINK,
			GUID_FK		 = '',
			NOM_ZN		 = ZS.NUMBER,
			DATE_ZN		 = ZS.DATE,
			NAME_UBP 	 = ZS.DEP_FNAME, 
			KOD_UBP		 = case @cCodeOpt when 1 then ZS.DEP_UBP else '' end,
			NAME_TOFK	 = ZS.TOFK_NAME,
			KOD_TOFK	 = ZS.TOFK_CODE,
			LS_PAY		 = ZS.ACC_CODE,
			NOM_BO		 = ISNULL (ZS.NUM_BO, ''),
			FAIP_CODE	 = space(14),
			INN_UBP		 = ZS.DEP_INN,
			KPP			 = ZS.DEP_KPP,
			CARD_NUM	 = ZS.CARD_CODE, 
			NAME_V_SR	 = cast(ZS.VID_SR as char(1)),
			DOL_ISP		 = ZS.EMP_POST,
			ISP_F		 = ZS.EMP_F,
			ISP_I		 = ZS.EMP_I,
			ISP_O		 = ZS.EMP_O,
			DOL_RUK		 = case @iPostRuk when 1 then B.POST_NAME else '' end,
			NAME_RUK	 = B.SHORT_NAME,
			DOL_BUH		 = case @iPostGl when 1 then GB.POST_NAME else '' end,
			NAME_BUH 	 = GB.SHORT_NAME,
			SUMMA_ITOG	 = ZS.SUMMA,
			SUMMA_R2	 = (SELECT SUM(SUMMA) from dbo.RECEPTION_CArd_table_view ZT where ZT.LINK_UP = ZS.LINK),
			DATE_POD	 = ZS.DATE_POD

	FROM dbo.DOC_RECEPTION_CARD ZS
	left join dbo.GetOtvFaceData(NULL, 'Руководитель') B on ZS.DEP_LINK = B.LINK_DEP
	left join dbo.GetOtvFaceData(NULL, 'Главный бухгалтер') GB on ZS.DEP_LINK = GB.LINK_DEP
	where ZS.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId))

	-- Таблица 5 (ZSCH2)
	select  LINK 		 = ZT.LINK,
			LINK_UP		 = ZT.LINK_UP,
			POR_NUM 	 = ZT.record_no,
			TYPE_KBK	 = case ZT.KBK_TYPE when 1 then '10'
												when 2 then '20'
												when 4 then '31'
												when 8 then '32'
												else '' end,
			KBK			 = replace(rtrim(ZT.KBK_CODE),'.',''),
			ADD_KLASS	 = ZT.D_CL_CODE,
			PURPOSE		 = ZT.REASON,
			SUMR_KBK	 = ZT.SUMMA,
			NOTE		 = ZT.TITLE

	from dbo.RECEPTION_CArd_table_view ZT 
	where ZT.LINK_UP in (select LINK from dbo.BufferGetTableByID(@cBuffId))









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_N_BOL_FILL3]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_N_BOL_FILL3]

GO

CREATE PROCEDURE [dbo].SA_N_BOL_FILL3 
(
 @LINK_DOC INT OUTPUT, --Ссылка на документ.	
 @LINK_ARCH INT, --Ссылка на больничный
 @LINK_PAYS INT = NULL, --Ссылка на вид начисления
 @TYP_PERIOD TINYINT = 3, --Тип расчетного периода: 1- по текущему месяцу, 2- по двум предыдущим, 3- по 12 предудущим месяцам
 @LIMIT TINYINT = 3,--Тип предела: 1- 2 тарифа, 2- 1 МРОТ, 3- по установленному значению, 4 - без ограничений
 @RECALC TINYINT = 0, -- 0 Полный расчет. расчет начинается с таблицы 3 
			-- 1 - не надо рассчитывать по видам начислений
			-- 2 - не надо рассчитывать по месяцам
			-- 3 - не надо рассчитывать средние суммы
 @OPER TINYINT = 0, -- 1 - сформировать операции
 @LINK_DEP INT = NULL
)
AS

SET NOCOUNT ON

DECLARE
 @LINK_EMPL INT, --Ссылка на сотрудника
 @DATE_BEGIN DATETIME, --Начало больничного
 @DATE_BEGIN_P DATETIME, --Начало больничного
 @DATE_END DATETIME, --Окончание больничного
 @REF_TYP_ARHE INT, --Ссылка на вид больничного
 @STAGE_Y INT, --Стаж
 @STAGE_M INT, --Стаж
 @comment varchar(100),
 @extension_DIS int,
 @dekret tinyint
 
DECLARE @UNAME VARCHAR(30)
SET @UNAME = CASE WHEN DBO.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT10') = 1 THEN ISNULL(dbo.AdminGetUserFIO(default),'') ELSE '' END
SET @UNAME = @UNAME + CASE WHEN LEN(@UNAME) > 0 THEN ':' ELSE '' END

---инит
SELECT @LINK_EMPL = REF_EMPL, @LINK_PAYS = ISNULL(@LINK_PAYS,LINK_PAYS), @DATE_BEGIN = DATE1, @DATE_END = DATEADD(day,DAYS-1, DATE1),
	@REF_TYP_ARHE = REF_TYP_ARHE,  @STAGE_Y = NEPR_YEAR,  @STAGE_M = NEPR_MONTH,
	@comment = @UNAME + 'Начисление по Б/Л:' + ISNULL(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM([NAME_TYP_ARHE])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
	@extension_DIS = REF_DOC, @dekret = ISNULL(D.DEKRET,0),
	@LINK_DEP = ISNULL(@LINK_DEP,LINK_DEP)
FROM dbo.DIS D 
WHERE D.LINK = @LINK_ARCH

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

SET @TYP_PERIOD = 4 --За 2 года

-- Проверка на продолжение больничного листа
DECLARE @varKSRefDoc int
SET @varKSRefDoc = ISNULL((SELECT TOP 1 FIRST_LINK FROM dbo.DIS_FIRST WHERE LINK = @LINK_ARCH),@LINK_ARCH)

SET @DATE_BEGIN_P = ISNULL((SELECT TOP 1 DATE1 FROM dbo.DIS WHERE LINK = @varKSRefDoc),@DATE_BEGIN)

SET @RP = 2
---Определение расчетного периода
DECLARE @NUMBER VARCHAR(10), @DATE_DOC DATETIME

SELECT 
	@DATE_BEGIN_RP = dbo.DateBeginOfYear(DATE_BEGIN), 
	@DATE_DOC = D.[DATE],
	@LINK_DEP = D.LINK_DEP,
	@NUMBER = D.NUMBER
FROM
	DBO.SDOC D 
	INNER JOIN dbo.sdoc_adis SD ON SD.LINK_UP = D.LINK
WHERE 
	D.LINK = @LINK_DOC
	
IF ISNULL(@LINK_DOC,0)  = 0
BEGIN
	exec dbo.SALARY_NEXT_NUM @NUMBER OUT, 'DOCUMENTS_ADD_ARCHE'
	SET @DATE_DOC = (Select top 1 WORKDATE from dbo.USER_DATES)
END	

IF @DATE_BEGIN_RP IS NULL OR YEAR(@DATE_BEGIN_RP) >= YEAR(@DATE_BEGIN_P) - @RP
	SET @DATE_BEGIN_RP = dbo.ConvertDMY2Date(1,1,YEAR(@DATE_BEGIN_P)- @RP)

SET @DATE_END_RP = dbo.ConvertDMY2Date(31,12,YEAR(@DATE_BEGIN_RP) + (@RP-1))

---Учитываем заданные года для расчетного периода
DECLARE @YEAR1 INT, @YEAR2 INT, @YEAR_M INT
SELECT TOP 1 @YEAR1 = YEAR1, @YEAR2 = YEAR2 FROM dbo.DIS D INNER JOIN dbo.VAC_PERIOD_CHANGE C ON C.LINK_EMPL = D.REF_EMPL
WHERE D.LINK = @LINK_ARCH AND D.DATE1 BETWEEN C.DATE1 AND C.DATE2

IF ISNULL(@YEAR1,0) > 0 OR ISNULL(@YEAR2,0) > 0
BEGIN

	SET @YEAR_M = (CASE WHEN ISNULL(@YEAR1,0) > ISNULL(@YEAR2,0) THEN ISNULL(@YEAR1,0) ELSE ISNULL(@YEAR2,0) END)
	SET @YEAR1 = (CASE WHEN ISNULL(@YEAR1,0) <= ISNULL(@YEAR2,0) THEN ISNULL(@YEAR1,0) ELSE ISNULL(@YEAR2,0) END)
	SET @YEAR2 = @YEAR_M

	SET @DATE_BEGIN_RP = dbo.ConvertDMY2Date(1,1,@YEAR1)
	SET @DATE_END_RP = dbo.ConvertDMY2Date(31,12,@YEAR2)

END	
ELSE
BEGIN
	SET @YEAR1 = YEAR(@DATE_BEGIN_RP)
	SET @YEAR2 = YEAR(@DATE_END_RP)
END	
-----------------------------------------------------------------

SELECT TOP 1 @LINK_PERS = PERS_LINK,  @SystPay = SYST_PAY, @DEP_LINK = ISNULL(@DEP_LINK,DEP_LINK)
FROM dbo.EMPL WHERE LINK = @LINK_EMPL

--Количество ставок на начало больничного
DECLARE @EmplNumStake NUMERIC(5,2), @DEFAULT_KBK INT
SELECT @EmplNumStake = num_stake, @DEFAULT_KBK = LINK_KBK FROM dbo.SA_EMPLS_INFO(@DATE_BEGIN_P,@LINK_EMPL)
SET @DEFAULT_KBK = ISNULL((SELECT CH.NEW_LINK FROM dbo.SAL_SFIN_CHANGES(@DATE_BEGIN) CH WHERE CH.LINK = @DEFAULT_KBK),@DEFAULT_KBK)

 --если страховой стаж работника менее 6 месяцев, то предел ус-танавливается в размере 1 МРОТ
IF @STAGE_Y < 1 AND @STAGE_M < 6 
	SET @LIMIT = 2

--- Сохранить параметры расчёта
SELECT @varKSsoLink = LINK FROM dbo.s_objects  WHERE CODE = 'DOCUMENTS_ADD_ARCHE'

EXECUTE dbo.SALARY_UPD_SDOC @LINK_DOC OUTPUT, @varKSsoLink, @NUMBER,@DATE_DOC,@comment,0,null,0, @LINK_DEP

IF not exists(select link_up from dbo.sdoc_adis  where link_up =@LINK_DOC)
		INSERT INTO dbo.sdoc_adis WITH (ROWLOCK) (LINK_UP,LINK_EMPL,LINK_PAY,DATE_BEGIN,SR_ZAR,SR_PREM,TYP_PERIOD,LIMIT,REF_DOC)
		VALUES (@LINK_DOC, @LINK_EMPL,@LINK_PAYS,@DATE_BEGIN_RP,0,0,@TYP_PERIOD,@LIMIT,@LINK_ARCH)
ELSE
		UPDATE dbo.sdoc_adis WITH (ROWLOCK) 
		SET 	LINK_EMPL=@LINK_EMPL, LINK_PAY=@LINK_PAYS, DATE_BEGIN=@DATE_BEGIN_RP, 
				SR_PREM=0, TYP_PERIOD=@TYP_PERIOD, LIMIT=@LIMIT, REF_DOC=@LINK_ARCH
		WHERE LINK_UP=@LINK_DOC

---------------------------------------------------------------------------------------
--Ограничивать количество оплачиваемых дней в каленарном году
DECLARE @ARCHE_OPT9 TINYINT
SET @ARCHE_OPT9 = dbo.sa_get_option_by_code('ARCHE_OPT9')

-- Больной член семьи по этому больничному
DECLARE @LINK_DIS_PERSON INT 

--Ограничения по количеству оплачиваемых дней по данному больничному
IF @ARCHE_OPT9 = 1 BEGIN

	SELECT @LINK_DIS_PERSON = ISNULL(REF_PERS_KID, @LINK_PERS) FROM dbo.SDOC_DIS WHERE LINK_UP = @LINK_ARCH

	DECLARE @MAX_DAYS INT, @MAX_DAYS_IVENT INT, @SUM_DAYS INT
	SELECT 
		  @MAX_DAYS = N.MAX_DAYS, 
		  @MAX_DAYS_IVENT = N.MAX_DAYS_IVENT,
		  @SUM_DAYS = ISNULL(
			( --Вычисляем количество дней больничных, за которые начислили больничные
			SELECT SUM(DAYS)
			FROM
			(	SELECT T.DATE1, [DAYS] = MAX(T.[DAYS])
				FROM
					dbo.SDOC D
					INNER JOIN dbo.SDOC_ADIS A ON D.LINK = A.LINK_UP
					INNER JOIN dbo.SDOC_ADIS_TABLE1 T ON T.LINK_UP = D.LINK
					INNER JOIN dbo.SDOC_DIS SD ON A.REF_DOC = SD.LINK_UP AND A.LINK_EMPL = SD.LINK_EMPL
				WHERE
					SD.[TYPE] = N.LINK
					AND YEAR(@DATE_DOC) BETWEEN YEAR(T.DATE1) AND YEAR(T.DATE2)
					AND SD.LINK_EMPL = @LINK_EMPL
					AND ISNULL(SD.REF_PERS_KID, @LINK_PERS) = @LINK_DIS_PERSON
					AND SD.LINK_UP <> @LINK_ARCH --Данный больничный не учитываем
					AND SD.DATE1 <= @DATE_BEGIN --Проверяем только по предыдущим больничным
				GROUP BY T.DATE1
				) D
			)
			,0)
	FROM 
			dbo.NETRUD N
	WHERE
		  N.LINK = @REF_TYP_ARHE
		  AND @ARCHE_OPT9 = 1
END	

SELECT @MAX_DAYS = ISNULL(@MAX_DAYS,9999), @MAX_DAYS_IVENT = ISNULL(@MAX_DAYS_IVENT,9999), @SUM_DAYS = ISNULL(@SUM_DAYS,0)

--Столько осталось оплатить
SET @MAX_DAYS = (CASE WHEN @MAX_DAYS > @SUM_DAYS THEN @MAX_DAYS - @SUM_DAYS ELSE 0 END)
--Можно оплатить столько дней
SET @MAX_DAYS_IVENT = (CASE WHEN @MAX_DAYS_IVENT < @MAX_DAYS THEN @MAX_DAYS_IVENT ELSE @MAX_DAYS END)
-----------------------------------------------------------------------------------

---Определение процента оплаты по стажу
DECLARE @RercStag NUMERIC(18,2)

SELECT TOP 1 
	@RercStag = P 
FROM 
	dbo.DOCUMENTS_ADD_ARCH_SPR1 SPR1 
WHERE 
	@DATE_BEGIN BETWEEN SPR1.DATE_BEGIN AND SPR1.DATE_END
	AND @STAGE_Y BETWEEN SPR1.STAGE1 AND SPR1.STAGE2

DECLARE
	@PERCENT numeric(18,2), --Процент оплаты
	@Opt  tinyint, -- 1 - учитывать настройки справочника, 0 - нет
	@Stag  tinyint, -- 1 за первые N дней учитывать проценты по стажу, 0 - использовать указанй процент Perc1
	@Stag2  tinyint, -- 1 за последующие дни учитывать проценты по стажу, 0 - использовать указанй процент Perc2
	@Day1g  INT, --- количество первых дней, которые оплачивается Perc1
	@Perc1  numeric(18,2),
	@Perc2  numeric(18,2),
	@Day2_Payer  tinyint -- 0 - Первые два дня больничного оплачивает ФСС, 1 - Первые два дня больничного оплачивает Работодатель

SELECT @Stag = ISNULL(stag,0), @Stag2 = ISNULL(stag2,0), @Day2_Payer = (CASE WHEN ISNULL(@extension_DIS,0) = 0 THEN ISNULL(day2_payer,0) ELSE 0 END), 
	@Opt = ISNULL(opt,0), @Perc1 = ISNULL(perc1,0), @Perc2 = ISNULL(perc2,0),
	@Day1g = (CASE WHEN ISNULL(day1,0) = 1 THEN 0 ELSE ISNULL(day1,0) END) 
FROM DBO.KD_NETRUD where link = @REF_TYP_ARHE

IF @RECALC = 0  --- Расчет сумм по видам начислений
BEGIN
	--- Промежуточная база расчета
	CREATE TABLE #BASE1 (
		PERIOD DATETIME,
		CODE_PAY VARCHAR(254),
		NAME_PAY VARCHAR(254), 
		WAY_CALC INT,
		LINK_PAY INT,
		SUMMA NUMERIC(18,2),
		KOEF  NUMERIC(18,2),
		LINK_INC INT,
		LINK_VKR INT,
		DATE1 DATETIME,
		DATE2 DATETIME
	)

	DECLARE @Cur1 CURSOR, @CUR_EPML INT
	DECLARE @Cur2 CURSOR, @M INT, @Y INT, @PER DATETIME

	DECLARE @ARCHE_OPT4 TINYINT
	SET @ARCHE_OPT4 = dbo.sa_get_option_by_code('ARCHE_OPT4')

	SET @Cur1 = CURSOR FORWARD_ONLY
	FOR SELECT DISTINCT LINK FROM dbo.EMPL E-- INNER JOIN dbo.EMPL_STATUS(@DATE_BEGIN) S on E.link = S.empl_link --AND STATUS <= 2
		WHERE DEP_LINK = @LINK_DEP AND (@ARCHE_OPT4 = 1 AND PERS_LINK = @LINK_PERS) OR (@ARCHE_OPT4 = 0 AND E.link = @LINK_EMPL)

	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @CUR_EPML
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			
			SET @Cur2 = CURSOR FORWARD_ONLY
			FOR SELECT m, y, DATE_BEGIN FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) WHERE Y = @YEAR1 OR Y = @YEAR2
			OPEN @Cur2
			FETCH NEXT FROM @Cur2 INTO @M, @Y, @PER
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN
			
				INSERT INTO #BASE1 (CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, KOEF, LINK_INC, LINK_VKR, DATE1, DATE2)
				exec dbo.SALARY_BASE_SUM_PAY_MONTH_DIF_PERIODS @LINK_PAYS, @CUR_EPML, @M, @Y			
				
				UPDATE #BASE1 SET PERIOD = @PER WHERE PERIOD IS NULL
				UPDATE #BASE1 SET LINK_VKR = @DEFAULT_KBK WHERE LINK_VKR IS NULL
			
				END
				FETCH NEXT FROM @Cur2 INTO @M, @Y, @PER
			END
		
			CLOSE @Cur2
			DEALLOCATE @Cur2

		END
		FETCH NEXT FROM @Cur1 INTO @CUR_EPML
	END
	
	CLOSE @Cur1 
	DEALLOCATE @Cur1

	INSERT INTO #BASE1 (PERIOD, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, KOEF, LINK_INC, LINK_VKR, DATE1, DATE2)
	SELECT dbo.ConvertDMY2Date(01,12,YEAR_SAL), '---', 'Заработок у других работодателей', 1, 0, SUMMA, 1, 0, @DEFAULT_KBK, dbo.ConvertDMY2Date(01,12,YEAR_SAL), dbo.ConvertDMY2Date(31,12,YEAR_SAL)  
	FROM [dbo].[SAL_OTHER_DEP] 
	WHERE ACTIVE = 1 AND YEAR_SAL IN (@YEAR1,@YEAR2) AND LINK_EMPL = @LINK_EMPL 

	/*Заменяем источники финансирования в базовых начислениях с учетом истории изменений источников*/
	UPDATE B SET B.LINK_VKR = CH.NEW_LINK
	FROM #BASE1 B INNER JOIN dbo.SAL_SFIN_CHANGES(@DATE_BEGIN) CH ON CH.LINK = B.LINK_VKR

	--- Определим, делать ли расчет в разрезе КБК
	DECLARE @ARCHE_OPT5 TINYINT
	SET @ARCHE_OPT5 = dbo.sa_get_option_by_code('ARCHE_OPT5')

	--
	Select 
		PERIOD = dbo.ConvertDMY2Date(31,12,YEAR(MIN(PERIOD))), PERIOD1 = YEAR(PERIOD), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, 
		SUMMA = SUM( CASE WHEN WAY_CALC = 6 AND (DATEDIFF(MONTH,DATE1, DATE2) + 1) <> 0 AND @UCHET_PREM = 1 THEN 
					CONVERT(NUMERIC(18,2), SUMMA * 
						(
							(DATEDIFF(MONTH,CASE WHEN DATE1 <= dbo.ConvertDMY2Date(1,1,@YEAR1) THEN dbo.ConvertDMY2Date(1,1,@YEAR1) ELSE DATE1 END,
								CASE WHEN DATE2 >= dbo.ConvertDMY2Date(31,12,@YEAR1) THEN dbo.ConvertDMY2Date(31,12,@YEAR1) ELSE DATE2 END) + 1)
						+	CASE WHEN @YEAR1 <> @YEAR2 THEN
								(DATEDIFF(MONTH,CASE WHEN DATE1 <= dbo.ConvertDMY2Date(1,1,@YEAR2) THEN dbo.ConvertDMY2Date(1,1,@YEAR2) ELSE DATE1 END,
									CASE WHEN DATE2 >= dbo.ConvertDMY2Date(31,12,@YEAR2) THEN dbo.ConvertDMY2Date(31,12,@YEAR2) ELSE DATE2 END) + 1)								
							ELSE 0 END
						)
						/ (DATEDIFF(MONTH,DATE1, DATE2) + 1))
				ELSE SUMMA END),
		KOEF, LINK_INC, LINK_VKR = (CASE WHEN @ARCHE_OPT5 = 1 then LINK_VKR else @DEFAULT_KBK end)
	INTO #BASE
	from #BASE1 
	group by YEAR(PERIOD), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, KOEF, LINK_INC, (CASE WHEN @ARCHE_OPT5 = 1 then LINK_VKR else @DEFAULT_KBK end)

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

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

	DELETE FROM dbo.SDOC_ADIS_TABLE3  WHERE LINK_UP = @LINK_DOC

	DECLARE @SCRIPT VARCHAR(8000)
	
	SET @SCRIPT = ' INSERT INTO dbo.SDOC_ADIS_TABLE3 (LINK_UP, ORDERS, LINK_PAY, LINK_KBK, SUMMA1, SUMMA2)'  
			+ ' Select ' + CONVERT(VARCHAR(20),@LINK_DOC) + ', 0, LINK_PAY, LINK_VKR'  
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = @YEAR1 )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) <= @YEAR1 ))
				+ ',0)' ELSE ',0' END
			+ CASE WHEN @YEAR1 <> @YEAR2 AND EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = @YEAR2 )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) <= @YEAR2 ))
				+ ',0)' ELSE ',0' END
		+ ' from ' + @PAYS_MONTS

	EXEC  (@SCRIPT)

	SET @I = 0
	UPDATE dbo.SDOC_ADIS_TABLE3  
	SET @I = @I+1, ORDERS = @I
	WHERE LINK_UP = @LINK_DOC
	
END -- IF @RECALC = 0

-- Время
DECLARE @WTIME1 TABLE(M INT, Y INT, [DAYS] NUMERIC(18,2))
DECLARE @WTIME TABLE(Y INT, [DAYS] NUMERIC(18,2))

INSERT INTO @WTIME1 (M,Y,[DAYS])
SELECT m,y, 
	CASE WHEN @TYP_PERIOD > 1 THEN 
		ISNULL(CONVERT(NUMERIC(4,0),dbo.SA_CALENDAR_DAYS3_FN(@LINK_EMPL,M,Y)),0)
	ELSE DATEDIFF(DAY,@DATE_BEGIN_RP, @DATE_END_RP)+1 END
FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) WHERE Y = @YEAR1 OR Y = @YEAR2

--Если нет календарных дней, считаем календарное в году
IF NOT EXISTS (SELECT * FROM @WTIME1 WHERE [DAYS] > 0)
	INSERT INTO @WTIME1 (Y,M,[DAYS])
	SELECT 
		Y, M, DAY(dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,m,y)))
	FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) WHERE Y = @YEAR1 OR Y = @YEAR2

DECLARE @DAYS2YEAR INT
SET @DAYS2YEAR = ISNULL((SELECT SUM(DAY(dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,m,y)))) FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) WHERE Y = @YEAR1 OR Y = @YEAR2 ),730)

--
INSERT INTO @WTIME (Y,[DAYS])
SELECT Y, SUM([DAYS]) FROM @WTIME1 GROUP BY Y

--
IF @RECALC < = 1 --- Расчет сумм по месяцам
BEGIN
	-- Расчет отработанного времени для каждого отрезочка времени
	---

	DECLARE @TABLE2 TABLE (Y INT, M INT, LINK_KBK INT, SUMMA_ZP NUMERIC(18,2), SUMMA_PR NUMERIC(18,2), [DAYS] INT, [HOURS] NUMERIC(18,2), DAYS_NORM INT, HOURS_NORM NUMERIC(18,2))
	INSERT INTO @TABLE2
	SELECT
		Y = T.Y,
		M = 12,
		ISNULL(B.LINK_KBK,@DEFAULT_KBK),
		SUMMA_ZP = SUM(SUMMA),
		SUMMA_PR = 0,
		ISNULL((SELECT SUM([DAYS]) FROM @WTIME T1 WHERE T1.Y = T.Y),0),
		0,0,0
	FROM 
		@WTIME T LEFT JOIN
		(
		Select PERIOD = dbo.DateEndOfYear(@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfYear(@DATE_BEGIN_RP), 
			DATE2 = dbo.DateEndOfYear(@DATE_BEGIN_RP),	
			SUMMA = T3.SUMMA1 
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA1,0) <> 0
	UNION ALL 
		Select PERIOD = dbo.DateEndOfYear(@DATE_END_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfYear(@DATE_END_RP), 
			DATE2 = dbo.DateEndOfYear(@DATE_END_RP),	
			SUMMA = T3.SUMMA2  
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA2,0) <> 0
	) AS B ON T.Y = YEAR(B.PERIOD)
	GROUP BY
		T.Y, B.LINK_KBK

	----
	DECLARE @LINK_PAY_FSS INT	
	SET @LINK_PAY_FSS = (SELECT TOP 1 LINK FROM dbo.PAYS WHERE [OBJECT] = 3 AND WAY_CALC = 2)

	----
	UPDATE @TABLE2
	SET SUMMA_PR = 
		(
			SELECT MAX(PREDEL) FROM dbo.DICTIONARY_RANGE D
			WHERE LINK_PAYS = @LINK_PAY_FSS 
					AND TARIF = 1 
					AND [PERCENT] > 0 
					AND [DATE] = (SELECT TOP 1 [DATE] 
										FROM dbo.DICTIONARY_RANGE D1 
										WHERE D1.TARIF = D.TARIF 
												AND D1.LINK_PAYS = D.LINK_PAYS 
												AND [DATE] <= dbo.ConvertDMY2Date(1,1,(CASE WHEN Y < 2010 THEN 2010 ELSE Y END))
									ORDER BY [DATE] DESC) 
		 )


	DECLARE @CurPR CURSOR, @y1 INT, @m1 INT, @y2 INT, @m2 INT, @link_kbk1 INT, @SUM_KBK NUMERIC(18,2)
	
	SET @CurPR = CURSOR FORWARD_ONLY

	FOR select y, m, link_kbk from @TABLE2 order by y, m
	
	OPEN @CurPR
	FETCH NEXT FROM @CurPR INTO @y1, @m1, @link_kbk1
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN

			IF ISNULL(@y2,0) <> ISNULL(@y1,0) OR ISNULL(@m2,0) <> ISNULL(@m1,0)
				SELECT @SUM_KBK = 0, @y2 = @y1, @m2 = @m1

			UPDATE @TABLE2 SET HOURS_NORM = CASE WHEN ISNULL(SUMMA_ZP,0) > ISNULL(SUMMA_PR-@SUM_KBK,0) 
												THEN CASE WHEN ISNULL(SUMMA_PR-@SUM_KBK,0) > 0 THEN ISNULL(SUMMA_PR-@SUM_KBK,0) ELSE 0 END
												ELSE ISNULL(SUMMA_ZP,0) END
			WHERE @y1 = Y AND @m1 = M AND isnull(@link_kbk1,0) = isnull(link_kbk,0)

			SET @SUM_KBK = @SUM_KBK + ISNULL( (SELECT SUMMA = SUMMA_ZP	FROM @TABLE2 WHERE @y1 = Y AND @m1 = M AND isnull(@link_kbk1,0) = isnull(link_kbk,0)),0)

		END
	
		FETCH NEXT FROM @CurPR INTO @y1, @m1, @link_kbk1
	END
	
	CLOSE @CurPR
	DEALLOCATE @CurPR

	UPDATE A
	SET SUMMA_ZP = 
		CASE WHEN (SELECT SUM(B.SUMMA_ZP) FROM @TABLE2 B WHERE A.Y = B.Y AND A.M = B.M) > 0 THEN
						A.SUMMA_ZP / (SELECT SUM(B.SUMMA_ZP) FROM @TABLE2 B WHERE A.Y = B.Y AND A.M = B.M)
						* (SELECT SUM(B.HOURS_NORM) FROM @TABLE2 B WHERE A.Y = B.Y AND A.M = B.M)
					ELSE 0 END	
	FROM @TABLE2 A

	UPDATE @TABLE2 SET SUMMA_PR = 0, HOURS_NORM = 0

	---
	DELETE FROM dbo.SDOC_ADIS_TABLE2  WHERE LINK_UP = @LINK_DOC
	
	INSERT INTO dbo.SDOC_ADIS_TABLE2 (LINK_UP, ORDERS, PERIOD, SUMMA, SUMMA_PREM, [DAYS], [HOURS], DAYS_N, HOURS_N, LINK_KBK)
	SELECT  @LINK_DOC, 0, dbo.ConvertDMY2Date(1, M, Y), SUMMA_ZP, SUMMA_PR, [DAYS],[HOURS],DAYS_NORM,HOURS_NORM, LINK_KBK
	FROM @TABLE2
	ORDER BY Y, M, LINK_KBK

	SET @I = 0
	UPDATE dbo.SDOC_ADIS_TABLE2  
	SET @I = @I+1, ORDERS = @I
	WHERE LINK_UP = @LINK_DOC
END	--IF @RECALC < = 1

DECLARE @RAION NUMERIC(18,2)
exec dbo.SA_EMPL_RAION_KOEF_BL @RAION OUT, @LINK_EMPL, @DATE_BEGIN

SET @RAION = CASE WHEN ISNULL(@RAION,0) <1 THEN 1 ELSE ISNULL(@RAION,0) END

DECLARE @SUM_LIMIT NUMERIC(18,4), @MINROT NUMERIC(18,2)
SET @MINROT = dbo.minrot2(@DATE_BEGIN) * (CASE WHEN @EmplNumStake <= 1 THEN @EmplNumStake ELSE 1 END) * 24

IF @RECALC < = 2 --- Расчет периодов больничного и определение средних сум
BEGIN		
	---Периоды больничного
	DECLARE
	 @DATE_RAB_END DATETIME,
	 @DATE_B DATETIME,
	 @R int	-- Первые 3 дня за счет работодателя
	
	---
	SELECT @R = @Day2_Payer * 3
	SELECT @DATE_RAB_END = DATEADD(DAY,@R-1,@DATE_BEGIN), @DATE_B = CASE WHEN @R > 0 THEN DATEADD(DAY,@R,@DATE_BEGIN) ELSE @DATE_BEGIN END

	/*Если это продолжение, то за счет работодателя ни чего не оплачивается, предполагается, что первый больничный был не менее 2-х дней*/
	
	---Разбивка периодов на периоды по настройкам оплаты больничного
	DECLARE
	 @DATE_BEGIN1 DATETIME,
	 @DATE_END1 DATETIME 

	--Обработка продолжения б/л
	DECLARE @LINK_BL_OLD INT, @DATE_BEG_OLD DATETIME, @DATE_END_OLD DATETIME
	SET @LINK_BL_OLD = (SELECT TOP 1 REF_DOC FROM dbo.DIS WHERE LINK = @LINK_ARCH)

	/*УЧИТЫВАЕМ, ЧТО ЭТО МОЖЕТ БЫТЬ ПРОДОЛЖЕНИЕМ БОЛЬНИЧНОГО ЛИСТА*/
	--Периоды продолжаемого б/л	
	SELECT @DATE_BEG_OLD = DATE1, @DATE_END_OLD = DATE2 FROM dbo.DIS WHERE LINK = @LINK_BL_OLD
	--расширить периоды за счет других продолжений
	IF EXISTS (SELECT LINK FROM dbo.DIS WHERE REF_DOC = @LINK_BL_OLD AND LINK <> @LINK_ARCH AND DATE1 < @DATE_BEGIN)
		SET @DATE_END_OLD = (SELECT MAX(DATE2) FROM dbo.DIS WHERE REF_DOC = @LINK_BL_OLD AND LINK <> @LINK_ARCH AND DATE1 < @DATE_BEGIN)

	IF @DATE_BEG_OLD IS NOT NULL
	BEGIN
		SET @Day1g = @Day1g - (DATEDIFF(DAY,@DATE_BEG_OLD,@DATE_END_OLD) + 1)
		SET @Day1g = CASE WHEN @Day1g < 0 THEN 0 ELSE @Day1g END
	END

	SET @DATE_END1 = (CASE WHEN DATEADD(DAY,@Day1g-1,@DATE_BEGIN) < @DATE_END THEN DATEADD(DAY,@Day1g-1,@DATE_BEGIN) ELSE @DATE_END END)
	SET @DATE_BEGIN1 = (CASE WHEN @DATE_END1 +1 < @DATE_END THEN @DATE_END1 +1 ELSE @DATE_END END)

	--== ФОРМИРНОВАНИЕ ПЕРИОДОВ ДЛЯ ОПЛАТЫ В РАЗРЕЗЕ ГОДА, МЕСЯЦА, ПЛАТЕЛЬЩИКА И ПРОЦЕНТОВ
	DECLARE @PERIODY TABLE ( ord int identity(1,1), DATE_BEGIN DATETIME, DATE_END DATETIME, R TINYINT, PERC NUMERIC(18,2), DH NUMERIC(18,2), DH_NORM NUMERIC(18,6), I TINYINT, SUM_LIMIT NUMERIC(20,4))
	
	--- 1. Разбивка на периоды по плательщикам и календарным месяцам
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, R, PERC, I)
	--- Определение плательщика
	select 
		DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_RAB_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_RAB_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 1, PERC = 0.00, 1 --Первое преобразование
	from dbo.months_ex(@DATE_BEGIN, @DATE_RAB_END)
	WHERE @R > 0
	UNION ALL
	select 
		DATE_BEGIN = (CASE WHEN @DATE_B > DATE_BEGIN THEN @DATE_B ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 0, PERC = 0.00, 1
	from dbo.months_ex(@DATE_B, @DATE_END)
	UNION
	--- Определение процента в зависимости от настроек больничного
	SELECT  
		DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_END1 < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END1 ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 0, PERC = CASE WHEN @Stag = 0 THEN @Perc1 ELSE @RercStag END, 1
	from dbo.months_ex(@DATE_BEGIN, @DATE_END1 )
	WHERE 	ISNULL(@OPT,0) = 1 
	UNION ALL
	SELECT  
		DATE_BEGIN = (CASE WHEN @DATE_BEGIN1 > DATE_BEGIN THEN @DATE_BEGIN1 ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 0, PERC = CASE WHEN @Stag2 = 0 THEN @Perc2 ELSE @RercStag END, 1
	from dbo.months_ex(@DATE_BEGIN1, @DATE_END )
	WHERE 	ISNULL(@OPT,0) = 1
	ORDER BY DATE_BEGIN, DATE_END

	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, R, PERC, I)
	--- Установка процента, если настройки не заданы
	SELECT  
		DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 0, PERC = @RercStag, 1
	from dbo.months_ex(@DATE_BEGIN, @DATE_END )
	WHERE 	ISNULL(@OPT,0) = 0 
	ORDER BY DATE_BEGIN, DATE_END

	--- 2. Все границы периодов
	DECLARE @PERIODY1 TABLE (ORD INT IDENTITY(1,1), PER DATETIME)
	INSERT INTO @PERIODY1 (PER)
	SELECT PER FROM (SELECT PER = DATE_BEGIN FROM @PERIODY UNION SELECT PER = DATE_END FROM @PERIODY) as P
	UNION ALL 
	SELECT PER FROM (SELECT PER = DATE_BEGIN FROM @PERIODY UNION SELECT PER = DATE_END FROM @PERIODY) as P
	WHERE PER = dbo.DateEndOfMonth(PER)
	ORDER BY PER	

	--- 3.Получение отрезков времени со сдвинутыми датами начала
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, I)
	SELECT 
		(CASE WHEN P1.PER = @DATE_BEGIN OR P1.PER = @DATE_END THEN P1.PER ELSE P1.PER + 1 END),
		ISNULL(P2.PER,P1.PER),
		2  --второе преобразование
	FROM 
		@PERIODY1 P1 LEFT JOIN @PERIODY1 P2 ON P1.ORD = P2.ORD - 1

	---Корректировка
	UPDATE @PERIODY
	SET DATE_BEGIN  = DATE_BEGIN + 1
	WHERE I = 2 AND DATE_BEGIN <> DATE_END AND DATE_BEGIN = dbo.DateEndOfMonth(DATE_BEGIN)

	--- 4. Исключение перекрывающихся периодов
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, I)
	SELECT AP.DATE_BEGIN, AP.DATE_END, 3 FROM @PERIODY AP
	WHERE AP.I = 2 AND NOT EXISTS (SELECT * FROM @PERIODY AP1 WHERE AP1.I = 2 AND AP.DATE_BEGIN > AP1.DATE_BEGIN AND AP.DATE_END <= AP1.DATE_END)

	-- Особый случай, когда боьничный один день
	IF @DATE_BEGIN = @DATE_END 
		UPDATE @PERIODY SET DATE_BEGIN = @DATE_BEGIN, DATE_END = @DATE_END
		WHERE DATE_END >= @DATE_BEGIN

	--- 5. Расстановка плательщика и процентов по периодам
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, I, R, PERC)
	Select 
		P3.DATE_BEGIN, P3.DATE_END, 4,
		R =  ISNULL((SELECT TOP 1 P1.R FROM @PERIODY P1 WHERE I = 1 AND P1.R = 1 AND (P3.DATE_BEGIN BETWEEN P1.DATE_BEGIN AND P1.DATE_END) AND (P3.DATE_END BETWEEN P1.DATE_BEGIN AND P1.DATE_END)  order by ord),0),
		PERC = ISNULL((SELECT TOP 1 P1.PERC FROM @PERIODY P1 WHERE I = 1 AND P1.PERC > 0 AND (P3.DATE_BEGIN BETWEEN P1.DATE_BEGIN AND P1.DATE_END) AND (P3.DATE_END BETWEEN P1.DATE_BEGIN AND P1.DATE_END) order by ord),0)
	FROM @PERIODY P3 
	WHERE P3.I = 3 
	
	--- 6. Соединение периодов
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, I, R, PERC)
	Select 
		MIN(DATE_BEGIN), MAX(DATE_END), 5, R, PERC
	FROM @PERIODY P4 
	WHERE P4.I = 4 
	GROUP BY YEAR(DATE_BEGIN), MONTH(DATE_BEGIN), R, PERC
	
	DECLARE @ARCHE_OPT13 INT --Не начисять суммы за счёт ФСС 
	SET @ARCHE_OPT13 = dbo.SA_GET_OPTION_BY_CODE('ARCHE_OPT13')
	IF @ARCHE_OPT13 = 1
		DELETE FROM @PERIODY WHERE I = 5 AND R = 0
	
	--== ПОЛУЧЕНИЕ ПЕРИОДОВ ЗАВЕРШЕНО!
	
	---Определение предела

	-- увеличенный на размер районного коэффициента
	--Сумма МРОТ должна быть в пределах количества ставок, т.к. по ней идет расчет за полностью отработанное время на полной ставке

	DECLARE @LINK_FSS INT, @MAX_SUM_FSS NUMERIC(18,2)
	SET @LINK_FSS = (SELECT TOP 1 LINK FROM dbo.PAYS WHERE [OBJECT] = 3 AND WAY_CALC = 2)
	
	DECLARE @T_MAX_SUM_FSS TABLE (SUMMA NUMERIC(18,2))

	----
	INSERT INTO @T_MAX_SUM_FSS (SUMMA)
	SELECT MAX_SUM_FSS = 
				(
					SELECT MAX(PREDEL) FROM dbo.DICTIONARY_RANGE D
					WHERE LINK_PAYS = @LINK_FSS 
							AND TARIF = 1 
							AND [PERCENT] > 0 
							AND [DATE] = (SELECT TOP 1 [DATE] 
												FROM dbo.DICTIONARY_RANGE D1 
												WHERE D1.TARIF = D.TARIF 
														AND D1.LINK_PAYS = D.LINK_PAYS 
														AND [DATE] <= dbo.ConvertDMY2Date(1,1,(CASE WHEN Y < 2010 THEN 2010 ELSE Y END))
											ORDER BY [DATE] DESC) 
				 )
	FROM 
		@WTIME T
		
	SET @MAX_SUM_FSS = (SELECT SUM(SUMMA) FROM @T_MAX_SUM_FSS)
		--(SELECT SUM(SUMMA)/(12*COUNT(*)) FROM @T_MAX_SUM_FSS)
	IF ISNULL(@MAX_SUM_FSS,0) = 0
		SET @MAX_SUM_FSS = dbo.sa_get_option_by_code('ARCHE_OPT1')

	DECLARE @D NUMERIC(18,6)
	SET @D = ISNULL((SELECT SUM([DAYS]) FROM 
			(SELECT PERIOD, MAX([DAYS]) AS DAYS FROM dbo.SDOC_ADIS_TABLE2 WHERE LINK_UP = @LINK_DOC	GROUP BY PERIOD) T
		),0)

	IF @D = 0 SET @D = 730--@DAYS2YEAR

	----
	UPDATE @PERIODY
	SET 

		DH = DATEDIFF(DAY,DATE_BEGIN, DATE_END)+1,
	
		DH_NORM = 
				CASE WHEN DATE_BEGIN <= '20091231' THEN 
					DAY(dbo.DateEndOfMonth(DATE_BEGIN))
				ELSE
					730
				END,			
		SUM_LIMIT = 
				CONVERT(NUMERIC(18,2),
					CASE @LIMIT
					WHEN 2 THEN @MINROT * @RAION -- в размере 1 МРОТ
					WHEN 3 THEN 
						CASE WHEN DATE_BEGIN <= '20091231' THEN 	
							(CASE WHEN @dekret = 0 THEN dbo.sa_get_option_by_code('ARCHE_OPT7') ELSE dbo.sa_get_option_by_code('ARCHE_OPT8') END) * @RAION 
						ELSE	
							-- !!! С 1 января 2010 года максимальный размер пособия одинаковый по все территории РФ!!!: Максимум без учета районныйх, но с учетом стажа
							@MAX_SUM_FSS
						END
					ELSE 0
					END 
				)				
	WHERE I = 5

	---------------------------------------------------------------------------------------
	--Откорректируем оплачиваемые дни за каждый период
	DECLARE @Cur3 CURSOR
	Declare @NEXT_DATE DATETIME

	IF @ARCHE_OPT9 = 1
	BEGIN
		SET @Cur3 = CURSOR FORWARD_ONLY

		FOR SELECT DATE_BEGIN FROM @PERIODY WHERE I = 5 AND YEAR(@DATE_DOC) BETWEEN YEAR(DATE_BEGIN) AND YEAR(DATE_END) ORDER BY DATE_BEGIN
		
		OPEN @Cur3
		FETCH NEXT FROM @Cur3 INTO @NEXT_DATE
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN

				UPDATE @PERIODY
				SET DH = (CASE WHEN DH < @MAX_DAYS_IVENT THEN DH ELSE @MAX_DAYS_IVENT END)
				WHERE I = 5 AND DATE_BEGIN = @NEXT_DATE
				
				SELECT @MAX_DAYS_IVENT = (CASE WHEN DH < @MAX_DAYS_IVENT THEN @MAX_DAYS_IVENT - DH ELSE 0 END)
				FROM @PERIODY
				WHERE I = 5 AND DATE_BEGIN = @NEXT_DATE

			END
		
			FETCH NEXT FROM @Cur3 INTO @NEXT_DATE
		END
		
		CLOSE @Cur3
		DEALLOCATE @Cur3
	END	
	---------------------------------------------------------------------------------------

	---
	DECLARE @REP_SUMMA_PR NUMERIC(18,2), @SUMMA_ZP NUMERIC(18,2), @SUMMA_PR NUMERIC(18,2), @NORM NUMERIC(18,2), @WORK NUMERIC(18,2), @SR_ZP NUMERIC(20,4)
	
	SELECT 
		@SUMMA_ZP = ISNULL(SUM(SUMMA),0),
		@SUMMA_PR = 0
	FROM dbo.SDOC_ADIS_TABLE2 WHERE LINK_UP = @LINK_DOC

	----	
	DECLARE @KBK_KOEF TABLE (LINK_KBK INT, KOEF NUMERIC(18,4))
	DECLARE @SR_ZP_R numeric(20,4)

	---	
	SET @SR_ZP = CONVERT(NUMERIC(18,2),ISNULL(@SUMMA_ZP,0) / @D)
	SET @SR_ZP_R = @SR_ZP

	IF ISNULL(@SR_ZP,0) = 0  BEGIN
		DELETE FROM @KBK_KOEF
		INSERT INTO @KBK_KOEF (LINK_KBK, KOEF) 
		SELECT @DEFAULT_KBK, 1
	END 
	ELSE BEGIN
		---
		DECLARE @S NUMERIC(18,2)
		SET @S = ISNULL((SELECT SUM(SUMMA) FROM dbo.SDOC_ADIS_TABLE2 WHERE LINK_UP = @LINK_DOC),0)

		INSERT INTO @KBK_KOEF (LINK_KBK, KOEF) 
		SELECT LINK_KBK, CASE WHEN @S <> 0 THEN SUM(SUMMA) / @S ELSE 0 END 
		FROM dbo.SDOC_ADIS_TABLE2  WHERE LINK_UP = @LINK_DOC 
		GROUP BY LINK_KBK
	END
	---
	DELETE FROM dbo.SDOC_ADIS_TABLE1  WHERE LINK_UP = @LINK_DOC
	INSERT INTO dbo.SDOC_ADIS_TABLE1 (LINK_UP, ORDERS, DATE1, DATE2, SUM_LIMIT, [DAYS], [HOURS], SR_ZP, SUMMA, PERC, PAYER, LINK_KBK, KOEF_KBK)
	SELECT @LINK_DOC, 0, DATE_BEGIN, DATE_END, 
		LIMIT = CONVERT(NUMERIC(20,2), P.SUM_LIMIT / DH_NORM),
		DH,--(CASE WHEN @SystPay = 1 THEN DH ELSE 0 END),
		0,--(CASE WHEN @SystPay = 1 THEN 0 ELSE DH END),
		SR_ZP = NULL,
		0,
		PERC,
		R,
		K.LINK_KBK,
		K.KOEF
	FROM @PERIODY P INNER JOIN @KBK_KOEF K ON 1=1
	WHERE I = 5
	ORDER BY DATE_BEGIN

	UPDATE sdoc_adis WITH (ROWLOCK) 
	SET 	LINK_EMPL = @LINK_EMPL, LINK_PAY=@LINK_PAYS, DATE_BEGIN=@DATE_BEGIN_RP, SR_ZAR=@SR_ZP_R, SR_PREM=@SUMMA_PR, TYP_PERIOD=@TYP_PERIOD, LIMIT=@LIMIT, REF_DOC=@LINK_ARCH, INSTRUCT = 3
	WHERE LINK_UP = @LINK_DOC
	
END --@RECALC <= 2 

DECLARE @ARCHE_OPT10 TINYINT -- Мин. размер пособия при отсутсвии заработка выплачивать с учётом районного коэффицента
SET @ARCHE_OPT10 = dbo.SA_GET_OPTION_BY_CODE('ARCHE_OPT10')

DECLARE @SR_ZP_MINI numeric(20,4)
SET @SR_ZP_MINI = @MINROT * (CASE WHEN @ARCHE_OPT10 = 1 THEN @RAION ELSE 1 END)  / 730--@DAYS2YEAR

SET @SR_ZP = ISNULL((SELECT TOP 1 SR_ZAR FROM dbo.sdoc_adis WHERE LINK_UP = @LINK_DOC),0)
SET @SR_ZP = CASE WHEN @SR_ZP < @SR_ZP_MINI THEN @SR_ZP_MINI ELSE @SR_ZP END

UPDATE dbo.SDOC_ADIS_TABLE1
SET 
	SR_ZP = convert(numeric(20,4),
			(CASE WHEN @SR_ZP < SUM_LIMIT OR @LIMIT = 4 AND @LIMIT <> 2 THEN @SR_ZP ELSE SUM_LIMIT END))
			* convert(numeric(20,4),(CASE WHEN PERC > 0 then PERC/100 else 0 end))
FROM 
	dbo.sdoc_adis A 
	INNER JOIN dbo.SDOC_ADIS_TABLE1 T ON A.LINK_UP = T.LINK_UP
WHERE 
	T.LINK_UP = @LINK_DOC AND KOEF_KBK IS NOT NULL


--Заменяю источник финансирования за счет ФСС
UPDATE dbo.SDOC_ADIS_TABLE1
SET 
	LINK_KBK = SF.[LINK_SS_SFIN]
FROM 
	dbo.sdoc_adis A 
	INNER JOIN dbo.SDOC_ADIS_TABLE1 T ON A.LINK_UP = T.LINK_UP
	INNER JOIN dbo.SAL_SFIN SF ON SF.LINK = T.LINK_KBK
WHERE 
	T.LINK_UP = @LINK_DOC AND PAYER = 0 AND SF.[LINK_SS_SFIN] IS NOT NULL


----
Select CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR, DAYS = SUM(CJ.DAYS), HOURS = SUM(CJ.HOURS), LINK_EKR, SUMMA = SUM(SUMMA)
INTO #SUM_OLD
from 
	dbo.SDOC_ADIS SA inner join dbo.CALCULATE_JURNAL CJ on CJ.LINK_DOC = SA.LINK_UP
	inner join dbo.sdoc d on CJ.LINK_DOC = d.link 
where
	ISNULL(@LINK_ARCH,0) > 0
	AND
	SA.REF_DOC = @LINK_ARCH
	and
	d.object = (Select top 1 link from s_objects where code = 'DOCUMENTS_ADD_ARCHE')
GROUP BY
	CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR, LINK_EKR

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

---- сопоставить старые
UPDATE dbo.SDOC_ADIS_TABLE1
SET 
	SUMMA_NEW = CONVERT(NUMERIC(18,2), T.SR_ZP * T.[DAYS] * KOEF_KBK),--(CASE WHEN @SystPay = 1 THEN T.[DAYS] ELSE T.[HOURS] END) * KOEF_KBK),
	SUMMA_OLD = ISNULL(SO.SUMMA,0),
	DAYS = COALESCE(T.DAYS,0) - COALESCE(SO.DAYS,0), 
	HOURS = COALESCE(T.HOURS,0) - COALESCE(SO.HOURS,0)
FROM 
	dbo.sdoc_adis A 
	INNER JOIN dbo.SDOC_ADIS_TABLE1 T ON A.LINK_UP = T.LINK_UP
	LEFT JOIN #SUM_OLD SO ON T.DATE1 = SO.DATE_BEGIN AND T.DATE2 = SO.DATE_END AND T.LINK_KBK = SO.LINK_VKR and PAYER = (CASE WHEN LINK_EKR=@LInkEKR213 then 0 else 1 end)
WHERE 
	T.LINK_UP = @LINK_DOC AND KOEF_KBK IS NOT NULL AND SR_ZP IS NOT NULL

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

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

--удалить пустые строки
DELETE FROM dbo.SDOC_ADIS_TABLE1
WHERE LINK_UP = @LINK_DOC AND ISNULL(SUMMA_NEW,0) = 0

SET @I = 0

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

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

---
SELECT @NUMBER = NUMBER,  @DATE_DOC = DATE from SDOC WHERE LINK = @LINK_DOC

if exists (select * from #SUM_OLD)
	set @comment = 'Перерасчет: ' + @comment

--- Сохрание расчета
EXECUTE dbo.SALARY_UPD_SDOC @LINK_DOC OUTPUT, @varKSsoLink, @NUMBER,@DATE_DOC,@comment,0,null,@SUMMA

IF @OPER = 1 
	exec dbo.SD_N_BOL_PROV @LINK_DOC

SET NOCOUNT OFF



GO


GRANT EXECUTE ON dbo.[SA_N_BOL_FILL3] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

CREATE           
PROCEDURE BB_EXPORT_ZS_16
	@cBuffId	varchar(30) = '',
	@cObjCode	varchar(30) = ''

AS
  DECLARE @iDepLink	int, @cCodeOpt int, @cExp2 int, @iLongFio tinyint, @iPostRuk tinyint, @iPostGl tinyint

set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())
set @cCodeOpt = dbo.sa_get_option_by_code('RECEPTION_CASH_OPTIONS_KODBP')
set @cExp2 = dbo.sa_get_option_by_code('RECEPTION_CASH_OPTIONS_EXP2')
set @iLongFio = dbo.sa_get_option_by_code('RECEPTION_CASH_FIO')
set @iPostRuk = dbo.sa_get_option_by_code('RECEPTION_CASH_POST_RUK')
set @iPostGl = dbo.sa_get_option_by_code('RECEPTION_CASH_POST_GL')



-- Таблица 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	= D.FULL_NAME
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
from dbo.DEPARTMENTS D
inner join dbo.TREASURY TOFK on D.TOFK_LINK = TOFK.LINK
where D.LINK = @iDepLink



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


	SELECT  LINK 		 = ZS.LINK,
			LINK_UP		 = ZS.LINK,
			GUID_FK		 = '',
			NOM_ZVK		 = ZS.NUMBER,
			DATE_ZVK		 = ZS.DATE,
			NAME_BUD	 = case ZS.dep_type WHEN 1 then ZS.BUDG_NAME else '' end,
			NAME_UBP_FO	 = case ZS.dep_type WHEN 1 then ZS.FO_NAME else '' end,
			OKPO_FO	 = case ZS.dep_type WHEN 1 then ZS.FO_OKPO else '' end,
			NAME_GRBS	 = case ZS.dep_type WHEN 1 then ZS.GRBS_NAME else ZS.UCHR_NAME end,
			GLAVA_GRBS	 = case ZS.dep_type WHEN 1 then ZS.GRBS_CODE else '' end,
			NAME_UBP_PAY 	 = ZS.DEP_FNAME, 
			KOD_UBP_PAY	 = case @cCodeOpt when 1 then ZS.DEP_UBP else '' end,
			LS_PAY		 = ZS.ACC_CODE,
			NAME_TOFK	 = ZS.TOFK_NAME,
			KOD_TOFK	 = ZS.TOFK_CODE,
			DATE_LIM	 = ZS.SROK,
			NOM_BO		 = ISNULL (ZS.NUM_BO, ''),
			DOL_RUK		 = case @iPostRuk when 1 then B.POST_NAME else '' end,
			NAME_RUK	 = B.SHORT_NAME,
			DOL_BUH		 = case @iPostGl when 1 then GB.POST_NAME else '' end,
			NAME_BUH 	 = GB.SHORT_NAME,
			DATE_POD	 = ZS.DATE_POD,
			DOL_ISP_DOV	 = ZS.EMP_POST,
			NAME_ISP_DOV = case @iLongFio when 1 then ZS.EMP_FIO else rtrim(ZS.EMP_NAME) end,
			NAME_DOV	 = ZS.ED_DOC,
			NOM_DOC		 = ZS.ED_NUM,
			ORG_DOC		 = ZS.ED_WHOM,
			DATE_DOC	 = ZS.ED_DATE,
			SUM_ITOG	 = ZS.SUMMA,
			NOM_ZS_FK	 = '',
			DATE_FK		 = '',
			DOL_ISP_FK	 = '',
			NAME_ISP_FK	 = '',
			TEL_ISP_FK	 = ''
	FROM dbo.DOCUMENTS_RECEPTION_CASH ZS
	left join dbo.GetOtvFaceData(NULL, 'Руководитель') B on ZS.DEP_LINK = B.LINK_DEP
	left join dbo.GetOtvFaceData(NULL, 'Главный бухгалтер') GB on ZS.DEP_LINK = GB.LINK_DEP
	where ZS.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId))

	-- Таблица 5 (ZSCH1)
	declare @tBlok5 table (	LINK		int, 
							LINK_UP		int, 
							SUMR_ZVK	numeric(18,2), 
							CHECK_NOM	varchar(15), 
							CHECK_SER	varchar(30), 
							DATE_CHECK	datetime, 
							DATE_CHECK_LIM datetime, 
							CHECK_KAS	varchar(2), 
							ORDERS		int identity)
	insert into @tBlok5(LINK, LINK_UP, SUMR_ZVK, CHECK_NOM, CHECK_SER, DATE_CHECK, DATE_CHECK_LIM, CHECK_KAS)
	SELECT  LINK 		 = ZS.LINK,
			LINK_UP		 = ZS.LINK,
			SUMR_ZVK	 = ZST.SUMMA,
			CHECK_NOM	 = ZS.CHEK_NO,
			CHECK_SER	 = ZS.CHEK_SER,
			DATE_CHECK	 = ZS.CHEK_DATE,
			DATE_CHECK_LIM = ZS.CHEK_SROK,
			CHECK_KAS	 = case ZST.KP when '' then ZS.KP else ZST.KP end
	FROM dbo.DOCUMENTS_RECEPTION_CASH ZS
	inner join (select LINK_UP, KP,sum(SUMMA) as SUMMA from dbo.RECEPTION_CASH_table_view group by LINK_UP, KP) ZST on ZST.LINK_UP = ZS.LINK
	where ZS.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId))

	if @cExp2 = 1
	begin
		update B5
		set LINK = - link
		from @tBlok5 B5
		where ORDERS not in (select max(orders) from @tBlok5 where LINK_UP = B5.LINK_UP group by LINK_UP)

		select * from @tBlok5 order by LINK_UP, orders 

	-- Таблица 6 (ZSCH2)
		select  LINK 		 = ZT.LINK,
				LINK_UP		 = ZT.LINK_UP,
				KOD_IST		 = cast(ZT.VID_SR as char(1)),
				TYPE_KBK	 = case ZT.KBK_TYPE when 1 then '10'
												 when 2 then '20'
												 when 4 then '31'
												 when 8 then '32'
												 else '' end,
				KBK			 = replace(rtrim(ZT.KBK_CODE),'.',''),
				ADD_KLASS	 = ZT.D_CL_CODE,
				SUMR_KBK	 = ZT.SUMMA,
				PURPOSE		 = case ZT.REASON when '' then CONVERT(VARCHAR(210), (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=ZT.LINK_UP and gpv.object=(select link from s_objects where code='RECEPTION_CASH_REASON'))) else ZT.REASON end,
				NOTE		 = ZT.TITLE

		from dbo.RECEPTION_CASH_table_view ZT 
		where ZT.LINK_UP in (select LINK from dbo.BufferGetTableByID(@cBuffId))
	end
	else
	begin
		select orders as LINK, LINK_UP, SUMR_ZVK, CHECK_NOM, CHECK_SER, DATE_CHECK, DATE_CHECK_LIM, CHECK_KAS 
		from @tBlok5 
		order by LINK_UP, orders 
		


	-- Таблица 6 (ZSCH2)
		select  LINK 		 = ZT.LINK,
				LINK_UP		 = CH.ORDERS,
				KOD_IST		 = cast(ZT.VID_SR as char(1)),
				TYPE_KBK	 = case ZT.KBK_TYPE when 1 then '10'
												 when 2 then '20'
												 when 4 then '31'
												 when 8 then '32'
												 else '' end,
				KBK			 = replace(rtrim(ZT.KBK_CODE),'.',''),
				ADD_KLASS	 = ZT.D_CL_CODE,
				SUMR_KBK	 = ZT.SUMMA,
				PURPOSE		 = case ZT.REASON when '' then CONVERT(VARCHAR(210), (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=ZT.LINK_UP and gpv.object=(select link from s_objects where code='RECEPTION_CASH_REASON'))) else ZT.REASON end,
				NOTE		 = ZT.TITLE

		from dbo.RECEPTION_CASH_table_view ZT
		inner join @tBlok5 CH ON CH.LINK_UP = ZT.LINK_UP and (ZT.KP = CH.CHECK_KAS or ZT.KP ='')
		where ZT.LINK_UP in (select LINK from dbo.BufferGetTableByID(@cBuffId))
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.[SA_N_BOL_FILL1]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_N_BOL_FILL1]

GO


CREATE PROCEDURE [dbo].SA_N_BOL_FILL1 
(
 @LINK_DOC INT OUTPUT, --Ссылка на документ.	
 @LINK_ARCH INT, --Ссылка на больничный
 @LINK_PAYS INT = NULL, --Ссылка на вид начисления
 @TYP_PERIOD TINYINT = 3, --Тип расчетного периода: 1- по текущему месяцу, 2- по двум предыдущим, 3- по 12 предудущим месяцам
 @LIMIT TINYINT = 3,--Тип предела: 1- 2 тарифа, 2- 1 МРОТ, 3- по установленному значению, 4 - без ограничений
 @RECALC TINYINT = 0, -- 0 Полный расчет. расчет начинается с таблицы 3 
			-- 1 - не надо рассчитывать по видам начислений
			-- 2 - не надо рассчитывать по месяцам
			-- 3 - не надо рассчитывать средние суммы
 @OPER TINYINT = 0, -- 1 - сформировать операции
 @LINK_DEP INT = NULL
)
AS

SET NOCOUNT ON

DECLARE
 @LINK_EMPL INT, --Ссылка на сотрудника
 @DATE_BEGIN DATETIME, --Начало больничного
 @DATE_BEGIN_P DATETIME, --Начало больничного
 @DATE_END DATETIME, --Окончание больничного
 @REF_TYP_ARHE INT, --Ссылка на вид больничного
 @STAGE_Y INT, --Стаж
 @STAGE_M INT, --Стаж
 @comment varchar(100),
 @extension_DIS int,
 @dekret tinyint,
 @NO_RAION TINYINT
 
DECLARE @UNAME VARCHAR(30)
SET @UNAME = CASE WHEN DBO.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT10') = 1 THEN ISNULL(dbo.AdminGetUserFIO(default),'') ELSE '' END
SET @UNAME = @UNAME + CASE WHEN LEN(@UNAME) > 0 THEN ':' ELSE '' END

---инит
SELECT @LINK_EMPL = REF_EMPL, @LINK_PAYS = ISNULL(@LINK_PAYS,LINK_PAYS), @DATE_BEGIN = DATE1, @DATE_END = DATEADD(day,DAYS-1, DATE1),
	@REF_TYP_ARHE = REF_TYP_ARHE,  @STAGE_Y = NEPR_YEAR,  @STAGE_M = NEPR_MONTH,
	@comment = @UNAME + 'Начисление по Б/Л:' + ISNULL(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM([NAME_TYP_ARHE])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
	@extension_DIS = REF_DOC, @dekret = ISNULL(D.DEKRET,0),
	@LINK_DEP = ISNULL(@LINK_DEP,LINK_DEP)
FROM dbo.DIS D 
WHERE D.LINK = @LINK_ARCH

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

SET @UCHET_PREM = ISNULL(dbo.sa_get_option_by_code('FURLOUGH_OPT9'),1)

-- Проверка на продолжение больничного листа
DECLARE @varKSRefDoc int
SET @varKSRefDoc = ISNULL((SELECT TOP 1 FIRST_LINK FROM dbo.DIS_FIRST WHERE LINK = @LINK_ARCH),@LINK_ARCH)

SET @DATE_BEGIN_P = ISNULL((SELECT TOP 1 DATE1 FROM dbo.SDOC_DIS WHERE LINK_UP = @varKSRefDoc),@DATE_BEGIN)

SELECT TOP 1 
 @RP = (CASE @TYP_PERIOD WHEN 1 THEN 0 WHEN 2 THEN 2 WHEN 3 THEN 12 ELSE 0 END),
 @LINK_PERS = PERS_LINK,  @SystPay = SYST_PAY, @DEP_LINK = DEP_LINK, 
 @DATE_BEGIN_RP = dbo.kd_DateBeginWork(LINK,@DATE_BEGIN_P), 
 @DATE_END_RP = dbo.kd_DateEndWork(LINK,@DATE_BEGIN_P), 
 @MAX_DATE = '29990101',
 @NO_RAION = ISNULL(NO_RAION,0) 
FROM dbo.EMPL WHERE LINK = @LINK_EMPL

DECLARE @NUMBER VARCHAR(10), @DATE_DOC DATETIME
---Определение расчетного периода
SELECT 
	@DATE_BEGIN_RP = dbo.DateBeginOfMonth( dbo.IS_MAX_DATE(@DATE_BEGIN_RP,DATEADD(MONTH, -@RP,@DATE_BEGIN_P))),
	@DATE_END_RP = dbo.DateEndOfMonth( dbo.IS_MIN_DATE(ISNULL(@DATE_END_RP,@MAX_DATE), DATEADD(MONTH, -(CASE WHEN @RP > 0 THEN 1 ELSE 0 END),@DATE_BEGIN_P)))

IF ISNULL(@LINK_DOC,0) <> 0
BEGIN
	SELECT 
		@DATE_BEGIN_RP = dbo.IS_MIN_DATE(@DATE_BEGIN_RP,dbo.DateBeginOfMonth(DATE_BEGIN)),
		@DATE_DOC = D.[DATE],
		@LINK_DEP = D.LINK_DEP,
		@NUMBER = D.NUMBER
	FROM
		DBO.SDOC D 
		INNER JOIN dbo.sdoc_adis SD ON SD.LINK_UP = D.LINK
	WHERE 
		D.LINK = @LINK_DOC
	
	--Минимальная дата между датой увольнения и расчётной датой окончания расчётного периода	
	SET @DATE_END_RP = dbo.IS_MIN_DATE( ISNULL(@DATE_END_RP,@MAX_DATE), dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1, @DATE_BEGIN_RP))) 
	--Минимальная дата между расчётной датой конца расч. периода и датой предшествующей наступлению больничного
	SET @DATE_END_RP = dbo.IS_MIN_DATE(@DATE_END_RP, DATEADD(MONTH, -(CASE WHEN @RP > 0 THEN 1 ELSE 0 END),@DATE_BEGIN_P))
END		

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

--- Способ расчета: (1) в рабочих или в (2) календарных днях
DECLARE @ARCHE_OPT2 TINYINT
SET @ARCHE_OPT2 = dbo.sa_get_option_by_code('ARCHE_OPT2')

IF (@ARCHE_OPT2 = 1 AND DATEDIFF(DAY,@DATE_BEGIN_RP, @DATE_END_RP) <90 ) -- При расчете в рабочих днях, если работник перед наступлением временной нетрудоспособности отработал менее 90 дней, то предел устанавливается в размере 1 МРОТ
	OR (@ARCHE_OPT2 = 2 AND @STAGE_Y < 1 AND @STAGE_M < 6) -- При расчете в календарных днях, если страховой стаж работника менее 6 месяцев, то предел ус-танавливается в размере 1 МРОТ
SET @LIMIT = 2

--- Если новый расчет, то получить линк документа
IF ISNULL(@LINK_DOC,0)  = 0
BEGIN
	exec dbo.SALARY_NEXT_NUM @NUMBER OUT, 'DOCUMENTS_ADD_ARCHE'
	SET @DATE_DOC = (Select top 1 WORKDATE from USER_DATES)
	exec dbo.SD_N_BOL_SAVE @LINK_DOC OUT, @NUMBER, @DATE_DOC, @LINK_PAYS, @comment, 0, @LINK_EMPL, 0, @TYP_PERIOD, @LIMIT, 0, @DATE_BEGIN_RP,   @LINK_ARCH, 0, @LINK_DEP
END

---------------------------------------------------------------------------------------
--Ограничивать количество оплачиваемых дней в каленарном году
DECLARE @ARCHE_OPT9 TINYINT
SET @ARCHE_OPT9 = dbo.sa_get_option_by_code('ARCHE_OPT9')

-- Больной член семьи по этому больничному
DECLARE @LINK_DIS_PERSON INT 

--Ограничения по количеству оплачиваемых дней по данному больничному
IF @ARCHE_OPT9 = 1 BEGIN

	SELECT @LINK_DIS_PERSON = ISNULL(REF_PERS_KID, @LINK_PERS) FROM dbo.SDOC_DIS WHERE LINK_UP = @LINK_ARCH

	DECLARE @MAX_DAYS INT, @MAX_DAYS_IVENT INT, @SUM_DAYS INT
	SELECT 
		  @MAX_DAYS = N.MAX_DAYS, 
		  @MAX_DAYS_IVENT = N.MAX_DAYS_IVENT,
		  @SUM_DAYS = ISNULL(
			( --Вычисляем количество дней больничных, за которые начислили больничные
			SELECT SUM(DAYS)
			FROM
			(	SELECT T.DATE1, [DAYS] = MAX(T.[DAYS])
				FROM
					dbo.SDOC D
					INNER JOIN dbo.SDOC_ADIS A ON D.LINK = A.LINK_UP
					INNER JOIN dbo.SDOC_ADIS_TABLE1 T ON T.LINK_UP = D.LINK
					INNER JOIN dbo.SDOC_DIS SD ON A.REF_DOC = SD.LINK_UP AND A.LINK_EMPL = SD.LINK_EMPL
				WHERE
					SD.[TYPE] = N.LINK
					AND YEAR(@DATE_DOC) BETWEEN YEAR(T.DATE1) AND YEAR(T.DATE2)
					AND SD.LINK_EMPL = @LINK_EMPL
					AND ISNULL(SD.REF_PERS_KID, @LINK_PERS) = @LINK_DIS_PERSON
					AND SD.LINK_UP <> @LINK_ARCH --Данный больничный не учитываем
					AND SD.DATE1 <= @DATE_BEGIN --Проверяем только по предыдущим больничным
				GROUP BY T.DATE1
				) D
			)
			,0)
	FROM 
			dbo.NETRUD N
	WHERE
		  N.LINK = @REF_TYP_ARHE
		  AND @ARCHE_OPT9 = 1
END	

SELECT @MAX_DAYS = ISNULL(@MAX_DAYS,9999), @MAX_DAYS_IVENT = ISNULL(@MAX_DAYS_IVENT,9999), @SUM_DAYS = ISNULL(@SUM_DAYS,0)

--Столько осталось оплатить
SET @MAX_DAYS = (CASE WHEN @MAX_DAYS > @SUM_DAYS THEN @MAX_DAYS - @SUM_DAYS ELSE 0 END)
--Можно оплатить столько дней
SET @MAX_DAYS_IVENT = (CASE WHEN @MAX_DAYS_IVENT < @MAX_DAYS THEN @MAX_DAYS_IVENT ELSE @MAX_DAYS END)
---------------------------------------------------------------------------------------

---Определение процента оплаты по стажу
DECLARE @RercStag NUMERIC(18,2)

SELECT TOP 1 @RercStag = P FROM dbo.DOCUMENTS_ADD_ARCH_SPR1 SPR1 
WHERE @DATE_BEGIN BETWEEN SPR1.DATE_BEGIN AND SPR1.DATE_END
	AND @STAGE_Y BETWEEN SPR1.STAGE1 AND SPR1.STAGE2

DECLARE
	@PERCENT numeric(18,2), --Процент оплаты
	@Opt  tinyint, -- 1 - учитывать настройки справочника, 0 - нет
	@Stag  tinyint, -- 1 за первые N дней учитывать проценты по стажу, 0 - использовать указанй процент Perc1
	@Stag2  tinyint, -- 1 за последующие дни учитывать проценты по стажу, 0 - использовать указанй процент Perc2
	@Day1g  INT, --- количество первых дней, которые оплачивается Perc1
	@Perc1  numeric(18,2),
	@Perc2  numeric(18,2),
	@Day2_Payer  tinyint -- 0 - Первые два дня больничного оплачивает ФСС, 1 - Первые два дня больничного оплачивает Работодатель

SELECT @Stag = ISNULL(stag,0), @Stag2 = ISNULL(stag2,0), @Day2_Payer = (CASE WHEN ISNULL(@extension_DIS,0) = 0 THEN ISNULL(day2_payer,0) ELSE 0 END), 
	@Opt = ISNULL(opt,0), @Perc1 = ISNULL(perc1,0), @Perc2 = ISNULL(perc2,0),
	@Day1g = (CASE WHEN ISNULL(day1,0) = 1 THEN 0 ELSE ISNULL(day1,0) END) 
FROM DBO.KD_NETRUD where link = @REF_TYP_ARHE

---
DECLARE @DEFAULT_KBK INT
SET @DEFAULT_KBK = (Select TOP 1 KBK.LINK_KBK FROM dbo.KU_EmplStafKBK(default) KBK WHERE KBK.LINK_EMPL = @LINK_EMPL)
SET @DEFAULT_KBK = ISNULL((SELECT CH.NEW_LINK FROM dbo.SAL_SFIN_CHANGES(@DATE_BEGIN) CH WHERE CH.LINK = @DEFAULT_KBK),@DEFAULT_KBK)

---
IF @RECALC = 0  --- Расчет сумм по видам начислений
BEGIN
	--- Промежуточная база расчета
	CREATE TABLE #BASE1 (
		PERIOD DATETIME,
		CODE_PAY VARCHAR(254),
		NAME_PAY VARCHAR(254), 
		WAY_CALC INT,
		LINK_PAY INT,
		SUMMA NUMERIC(18,2),
		KOEF  NUMERIC(18,2),
		LINK_INC INT,
		LINK_VKR INT,
		DATE1 DATETIME,
		DATE2 DATETIME
	)

	DECLARE @Cur1 CURSOR, @CUR_EPML INT
	DECLARE @Cur2 CURSOR, @M INT, @Y INT, @PER DATETIME

	DECLARE @ARCHE_OPT4 TINYINT
	SET @ARCHE_OPT4 = dbo.sa_get_option_by_code('ARCHE_OPT4')
	
	SET @Cur1 = CURSOR FORWARD_ONLY
	FOR SELECT DISTINCT LINK FROM dbo.EMPL E INNER JOIN dbo.EMPL_STATUS(@DATE_BEGIN) S on E.link = S.empl_link --AND STATUS <= 2
		WHERE DEP_LINK = @LINK_DEP AND (@ARCHE_OPT4 = 1 AND PERS_LINK = @LINK_PERS) OR (@ARCHE_OPT4 = 0 AND E.link = @LINK_EMPL)

	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @CUR_EPML
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			IF @TYP_PERIOD IN (2,3) 
			BEGIN
				SET @Cur2 = CURSOR FORWARD_ONLY
				FOR SELECT m, y, DATE_BEGIN FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) 
				OPEN @Cur2
				FETCH NEXT FROM @Cur2 INTO @M, @Y, @PER
				WHILE (@@fetch_status <> -1)
				BEGIN
					IF (@@fetch_status <> -2)
					BEGIN
				
					INSERT INTO #BASE1 (CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, KOEF, LINK_INC, LINK_VKR, DATE1, DATE2)
					exec dbo.SALARY_BASE_SUM_PAY_MONTH_DIF_PERIODS @LINK_PAYS, @CUR_EPML, @M, @Y			

					UPDATE #BASE1 SET PERIOD = @PER WHERE PERIOD IS NULL
					UPDATE #BASE1 SET LINK_VKR = @DEFAULT_KBK WHERE LINK_VKR IS NULL
				
					END
					FETCH NEXT FROM @Cur2 INTO @M, @Y, @PER
				END
			
				CLOSE @Cur2
				DEALLOCATE @Cur2

			END
	
		END
		FETCH NEXT FROM @Cur1 INTO @CUR_EPML
	END
	
	CLOSE @Cur1 
	DEALLOCATE @Cur1

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

		SET @TYP_PERIOD = 1

		---Определение расчетного периода
		SET @DATE_BEGIN_RP = dbo.DateBeginOfMonth(@DATE_BEGIN)
		SET @DATE_END_RP = dbo.DateEndOfMonth(@DATE_BEGIN)

	END

	---
	IF @TYP_PERIOD = 1

		INSERT INTO #BASE1 (PERIOD, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, KOEF, LINK_INC, LINK_VKR, DATE1, DATE2)
		select @DATE_BEGIN, P.CODE, P.NAME, P.WAY_CALC, S.LINK_PAY, S.SUMMA, 0, 0, S.LINK_KBK, @DATE_BEGIN_RP, dbo.DateEndOfMonth(@DATE_BEGIN) 
		from 
			dbo.SA_ALL_PAYS_ALL_DATE0(@LINK_EMPL, @DATE_BEGIN, DEFAULT, @LINK_DEP)  S 
			inner join dbo.pays P on s.link_pay = p.link
		where s.link_pay IN (Select T.PAY_LINK FROM dbo.group_pays(@LINK_PAYS) T)



	--- Если застрахованный не имел заработка, то расчет по его постоянным начислениям
	IF ISNULL((select SUM(SUMMA) from #BASE1),0) = 0 BEGIN
		INSERT INTO #BASE1 (PERIOD, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, KOEF, LINK_INC, LINK_VKR, DATE1, DATE2)
		SELECT @DATE_BEGIN_RP, CODE_PAYS, NAME_PAYS, WAY_CALC, LINK_PAYS, summa, 0, 0, LINK_KBK, @DATE_BEGIN_RP, dbo.DateEndOfMonth(@DATE_BEGIN_RP) FROM dbo.sa_all_pays_all(@LINK_EMPL, @DATE_BEGIN, DEFAULT, @LINK_DEP, DEFAULT)
		SET @TYP_PERIOD = 1
	END
	
	/*Заменяем источники финансирования в базовых начислениях с учетом истории изменений источников*/
	UPDATE B SET B.LINK_VKR = CH.NEW_LINK
	FROM #BASE1 B INNER JOIN dbo.SAL_SFIN_CHANGES(@DATE_BEGIN) CH ON CH.LINK = B.LINK_VKR
	
	--- Определим, делать ли расчет в разрезе КБК
	DECLARE @ARCHE_OPT5 TINYINT
	SET @ARCHE_OPT5 = dbo.sa_get_option_by_code('ARCHE_OPT5')

	----
	Select PERIOD = MIN(PERIOD), PERIOD1 = (YEAR(PERIOD) * 100 + MONTH(PERIOD)), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, 
	SUMMA = SUM( CASE WHEN WAY_CALC = 6 AND (DATEDIFF(MONTH,DATE1, DATE2) + 1) <> 0 AND @UCHET_PREM = 1 THEN 
					CONVERT(NUMERIC(18,2), SUMMA * 
						(DATEDIFF(MONTH,CASE WHEN DATE1 <= @DATE_BEGIN_RP THEN @DATE_BEGIN_RP ELSE DATE1 END,
								CASE WHEN DATE2 >= @DATE_END_RP THEN @DATE_END_RP ELSE DATE2 END) + 1)
						/ (DATEDIFF(MONTH,DATE1, DATE2) + 1))
				ELSE SUMMA END),
	KOEF, LINK_INC, LINK_VKR = (CASE WHEN @ARCHE_OPT5 = 1 then LINK_VKR else @DEFAULT_KBK end), DATE1, DATE2 
	INTO #BASE
	from #BASE1 
	group by (YEAR(PERIOD) * 100 + MONTH(PERIOD)), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, KOEF, LINK_INC, (CASE WHEN @ARCHE_OPT5 = 1 then LINK_VKR else @DEFAULT_KBK end), DATE1, DATE2 

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

	--Если у сотрудника указано "Не начислять районный", то рассчитываем без районного
	SET @FURLOUGH_OPT_REG_KOEF = (CASE WHEN @NO_RAION = 1 THEN 0 ELSE dbo.sa_get_option_by_code('ARCHE_OPT11') END)
	SET @FURLOUGH_OPT_NORTH_KOEF = dbo.sa_get_option_by_code('ARCHE_OPT12')

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

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

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

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

	DELETE FROM dbo.SDOC_ADIS_TABLE3  WHERE LINK_UP = @LINK_DOC
	
	DECLARE @SCRIPT VARCHAR(8000)
	SET @SCRIPT = ' INSERT INTO dbo.SDOC_ADIS_TABLE3 (LINK_UP, ORDERS, LINK_PAY, LINK_KBK, SUMMA1, SUMMA2, SUMMA3, SUMMA4, SUMMA5, SUMMA6, SUMMA7, SUMMA8, SUMMA9, SUMMA10, SUMMA11, SUMMA12)'  
			+ ' Select ' + CONVERT(VARCHAR(20),@LINK_DOC) + ', 0, LINK_PAY, LINK_VKR'  
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 

				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0' END
		+ ' from ' + @PAYS_MONTS

	exec (@SCRIPT)
	
	SET @I = 0
	UPDATE dbo.SDOC_ADIS_TABLE3  
	SET @I = @I+1, ORDERS = @I
	WHERE LINK_UP = @LINK_DOC
	
END -- IF @RECALC = 0

--IF @RECALC < = 2 --- Расчет сумм по месяцам
--BEGIN
--END

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

	---- Расчет отработанного времени для каждого отрезочка времени
	IF @ARCHE_OPT2 = 1 BEGIN

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

		INSERT INTO @WTIME (M,Y,DAYS,HOURS,DAYS_NORM,HOURS_NORM)
		---Данные по отработанному времени
		Select 
			P.M, P.Y, 
			DAYS = ISNULL(CONVERT(NUMERIC(4,0), DBO.SA_GET_EMPL_WD (@LINK_EMPL, 0, DEFAULT, dbo.ConvertDMY2Date(1,P.M,P.Y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,P.M,P.Y)), @LINK_GRAPH, 0) ),0), 
			HOURS = ISNULL(CONVERT(NUMERIC(10,2), DBO.SA_GET_EMPL_WH (@LINK_EMPL, 0, DEFAULT, dbo.ConvertDMY2Date(1,P.M,P.Y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,P.M,P.Y)), @LINK_GRAPH, 0) ),0),
			DAYS_NORM = ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL,P.M,P.Y)),0),
			HOURS_NORM = ISNULL(CONVERT(NUMERIC(10,2),dbo.NORM_HOURS(@LINK_EMPL,P.M,P.Y)),0)
		FROM 	
			dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) P 
		WHERE 
			dbo.ConvertDMY2Date(1,P.M,P.Y) between @DATE_BEGIN_RP and dbo.DateEndOfMonth(@DATE_END_RP)
		GROUP BY 
			P.M, P.Y 
		---
		DELETE FROM @WTIME WHERE HOURS = 0 OR DAYS = 0
	
	END ELSE BEGIN
		INSERT INTO @WTIME (M,Y,DAYS,HOURS)
		SELECT m,y, 
			CASE WHEN @TYP_PERIOD > 1 THEN 
				ISNULL(CONVERT(NUMERIC(4,0),dbo.SA_CALENDAR_DAYS_FN(@LINK_EMPL,M,Y)),0)
			ELSE DATEDIFF(DAY,@DATE_BEGIN_RP, @DATE_END_RP)+1 END,
			 0.00
		FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP)
		
		---
		UPDATE @WTIME
		--SET DAYS_NORM = DAYS, HOURS_NORM = 0
		SET DAYS_NORM = DAY(dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,m,y))), HOURS_NORM = 0
	END

	---
	DECLARE @TABLE2 TABLE (Y INT, M INT, LINK_KBK INT, SUMMA_ZP NUMERIC(18,2), SUMMA_PR NUMERIC(18,2), DAYS INT, HOURS NUMERIC(18,2), DAYS_NORM INT, HOURS_NORM NUMERIC(18,2))
	INSERT INTO @TABLE2
	SELECT  
		Y = T.Y, --YEAR(B.PERIOD),
		M = T.M, --MONTH(B.PERIOD),
		ISNULL(B.LINK_KBK,@DEFAULT_KBK),
		SUMMA_ZP = SUM( CASE WHEN WAY_CALC <> 6 THEN SUMMA ELSE 0 END),
		SUMMA_PR = SUM( CASE WHEN WAY_CALC = 6 THEN SUMMA ELSE 0 END),
		DAYS,HOURS,DAYS_NORM,HOURS_NORM
	FROM @WTIME T LEFT JOIN
		(
		Select PERIOD = DATEADD(MONTH,0,@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,0,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,0,@DATE_BEGIN_RP)),	
			SUMMA = T3.SUMMA1 
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA1,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,1,@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,1,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,1,@DATE_BEGIN_RP)),	
			SUMMA = T3.SUMMA2  
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA2,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,2,@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,2,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,2,@DATE_BEGIN_RP)),	
			SUMMA = T3.SUMMA3  
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA3,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,3,@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,3,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,3,@DATE_BEGIN_RP)),	
			SUMMA = T3.SUMMA4  
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA4,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,4,@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,4,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,4,@DATE_BEGIN_RP)),	
			SUMMA = T3.SUMMA5  
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA5,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,5,@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,5,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,5,@DATE_BEGIN_RP)),	
			SUMMA = T3.SUMMA6  
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA6,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,6,@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,6,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,6,@DATE_BEGIN_RP)),	
			SUMMA = T3.SUMMA7  
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA7,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,7,@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,7,@DATE_BEGIN_RP)), 

			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,7,@DATE_BEGIN_RP)),	
			SUMMA = T3.SUMMA8  
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA8,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,8,@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,8,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,8,@DATE_BEGIN_RP)),	
			SUMMA = T3.SUMMA9  
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA9,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,9,@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,9,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,9,@DATE_BEGIN_RP)),	
			SUMMA = T3.SUMMA10  
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA10,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,10,@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,10,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,10,@DATE_BEGIN_RP)),	
			SUMMA = T3.SUMMA11  
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA11,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,11,@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,1,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,1,@DATE_BEGIN_RP)),	
			SUMMA = T3.SUMMA12  
		FROM dbo.SDOC_ADIS_TABLE3 T3 WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA12,0) <> 0
	) AS B ON T.Y = YEAR(B.PERIOD) AND T.M = MONTH(B.PERIOD)
	LEFT JOIN dbo.PAYS P ON B.LINK_PAY = P.LINK 
	GROUP BY
		T.Y,T.M,B.LINK_KBK, DAYS,HOURS,DAYS_NORM,HOURS_NORM	

	-----
	DELETE FROM dbo.SDOC_ADIS_TABLE2  WHERE LINK_UP = @LINK_DOC
	
	INSERT INTO dbo.SDOC_ADIS_TABLE2 (LINK_UP, ORDERS, PERIOD, SUMMA, SUMMA_PREM, DAYS, HOURS, DAYS_N, HOURS_N, LINK_KBK)
	SELECT  @LINK_DOC, 0, dbo.ConvertDMY2Date(1, M, Y), SUMMA_ZP, SUMMA_PR, 
		DAYS,HOURS,DAYS_NORM,HOURS_NORM, LINK_KBK
	FROM @TABLE2
	ORDER BY Y, M, LINK_KBK

	SET @I = 0
	UPDATE dbo.SDOC_ADIS_TABLE2  
	SET @I = @I+1, ORDERS = @I
	WHERE LINK_UP = @LINK_DOC
END	--IF @RECALC < = 1

IF @RECALC < = 2 --- Расчет периодов больничного и определение средних сум
BEGIN		
	---Периоды больничного
	DECLARE
	 @DATE_RAB_END DATETIME,
	 @DATE_B DATETIME,
	 @R int	-- Первые 2 дня за счет работодателя
	
	---
	SELECT @R = @Day2_Payer * 2
	SELECT @DATE_RAB_END = DATEADD(DAY,@R-1,@DATE_BEGIN), @DATE_B = CASE WHEN @R > 0 THEN DATEADD(DAY,@R,@DATE_BEGIN) ELSE @DATE_BEGIN END

	/*Если это продолжение, то за счет работодателя ни чего не оплачивается, предполагается, что первый больничный был не менее 2-х дней*/
	
	---Разбивка периодов на периоды по настройкам оплаты больничного
	DECLARE
	 @DATE_BEGIN1 DATETIME,
	 @DATE_END1 DATETIME 

	--Обработка продолжения б/л
	DECLARE @LINK_BL_OLD INT, @DATE_BEG_OLD DATETIME, @DATE_END_OLD DATETIME
	SET @LINK_BL_OLD = (SELECT TOP 1 REF_DOC FROM dbo.DIS WHERE LINK = @LINK_ARCH)

	/*УЧИТЫВАЕМ, ЧТО ЭТО МОЖЕТ БЫТЬ ПРОДОЛЖЕНИЕМ БОЛЬНИЧНОГО ЛИСТА*/
	--Периоды продолжаемого б/л	
	SELECT @DATE_BEG_OLD = DATE1, @DATE_END_OLD = DATE2 FROM dbo.DIS WHERE LINK = @LINK_BL_OLD
	--расширить периоды за счет других продолжений
	IF EXISTS (SELECT LINK FROM dbo.DIS WHERE REF_DOC = @LINK_BL_OLD AND LINK <> @LINK_ARCH AND DATE1 < @DATE_BEGIN)
		SET @DATE_END_OLD = (SELECT MAX(DATE2) FROM dbo.DIS WHERE REF_DOC = @LINK_BL_OLD AND LINK <> @LINK_ARCH AND DATE1 < @DATE_BEGIN)

	IF @DATE_BEG_OLD IS NOT NULL
	BEGIN
		SET @Day1g = @Day1g - (DATEDIFF(DAY,@DATE_BEG_OLD,@DATE_END_OLD) + 1)
		SET @Day1g = CASE WHEN @Day1g < 0 THEN 0 ELSE @Day1g END
	END

	SET @DATE_END1 = (CASE WHEN DATEADD(DAY,@Day1g-1,@DATE_BEGIN) < @DATE_END THEN DATEADD(DAY,@Day1g-1,@DATE_BEGIN) ELSE @DATE_END END)
	SET @DATE_BEGIN1 = (CASE WHEN @DATE_END1 +1 < @DATE_END THEN @DATE_END1 +1 ELSE @DATE_END END)

	--== ФОРМИРНОВАНИЕ ПЕРИОДОВ ДЛЯ ОПЛАТЫ В РАЗРЕЗЕ ГОДА, МЕСЯЦА, ПЛАТЕЛЬЩИКА И ПРОЦЕНТОВ
	DECLARE @PERIODY TABLE ( ord int identity(1,1), DATE_BEGIN DATETIME, DATE_END DATETIME, R TINYINT, PERC NUMERIC(18,2), DH NUMERIC(18,2), DH_NORM NUMERIC(18,6), I TINYINT, SUM_LIMIT NUMERIC(20,4))
	
	--- 1. Разбивка на периоды по плательщикам и календарным месяцам
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, R, PERC, I)
	--- Определение плательщика
	select 
		DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_RAB_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_RAB_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 1, PERC = 0.00, 1 --Первое преобразование
	from dbo.months_ex(@DATE_BEGIN, @DATE_RAB_END)
	WHERE @R > 0
	UNION ALL
	select 
		DATE_BEGIN = (CASE WHEN @DATE_B > DATE_BEGIN THEN @DATE_B ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 0, PERC = 0.00, 1
	from dbo.months_ex(@DATE_B, @DATE_END)
	UNION
	--- Определение процента в зависимости от настроек больничного
	SELECT  
		DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_END1 < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END1 ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 0, PERC = CASE WHEN @Stag = 0 THEN @Perc1 ELSE @RercStag END, 1
	from dbo.months_ex(@DATE_BEGIN, @DATE_END1 )
	WHERE 	ISNULL(@OPT,0) = 1 
	UNION ALL
	SELECT  
		DATE_BEGIN = (CASE WHEN @DATE_BEGIN1 > DATE_BEGIN THEN @DATE_BEGIN1 ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 0, PERC = CASE WHEN @Stag2 = 0 THEN @Perc2 ELSE @RercStag END, 1
	from dbo.months_ex(@DATE_BEGIN1, @DATE_END )
	WHERE 	ISNULL(@OPT,0) = 1
	ORDER BY DATE_BEGIN, DATE_END

	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, R, PERC, I)
	--- Установка процента, если настройки не заданы
	SELECT  
		DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 0, PERC = @RercStag, 1
	from dbo.months_ex(@DATE_BEGIN, @DATE_END )
	WHERE 	ISNULL(@OPT,0) = 0 
	ORDER BY DATE_BEGIN, DATE_END

	--- 2. Все границы периодов
	DECLARE @PERIODY1 TABLE (ORD INT IDENTITY(1,1), PER DATETIME)
	INSERT INTO @PERIODY1 (PER)
	SELECT PER FROM (SELECT PER = DATE_BEGIN FROM @PERIODY UNION SELECT PER = DATE_END FROM @PERIODY) as P
	UNION ALL 
	SELECT PER FROM (SELECT PER = DATE_BEGIN FROM @PERIODY UNION SELECT PER = DATE_END FROM @PERIODY) as P
	WHERE PER = dbo.DateEndOfMonth(PER)
	ORDER BY PER	

	--- 3.Получение отрезков времени со сдвинутыми датами начала
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, I)
	SELECT 
		(CASE WHEN P1.PER = @DATE_BEGIN OR P1.PER = @DATE_END THEN P1.PER ELSE P1.PER + 1 END),
		ISNULL(P2.PER,P1.PER),
		2  --второе преобразование
	FROM 
		@PERIODY1 P1 LEFT JOIN @PERIODY1 P2 ON P1.ORD = P2.ORD - 1

	---Корректировка
	UPDATE @PERIODY
	SET DATE_BEGIN  = DATE_BEGIN + 1
	WHERE I = 2 AND DATE_BEGIN <> DATE_END AND DATE_BEGIN = dbo.DateEndOfMonth(DATE_BEGIN)

	--- 4. Исключение перекрывающихся периодов
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, I)
	SELECT AP.DATE_BEGIN, AP.DATE_END, 3 FROM @PERIODY AP
	WHERE AP.I = 2 AND NOT EXISTS (SELECT * FROM @PERIODY AP1 WHERE AP1.I = 2 AND AP.DATE_BEGIN > AP1.DATE_BEGIN AND AP.DATE_END <= AP1.DATE_END)

	-- Особый случай, когда боьничный один день
	IF @DATE_BEGIN = @DATE_END 
		UPDATE @PERIODY SET DATE_BEGIN = @DATE_BEGIN, DATE_END = @DATE_END
		WHERE DATE_END >= @DATE_BEGIN

	--- 5. Расстановка плательщика и процентов по периодам
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, I, R, PERC)
	Select 
		P3.DATE_BEGIN, P3.DATE_END, 4,
		R =  ISNULL((SELECT TOP 1 P1.R FROM @PERIODY P1 WHERE I = 1 AND P1.R = 1 AND (P3.DATE_BEGIN BETWEEN P1.DATE_BEGIN AND P1.DATE_END) AND (P3.DATE_END BETWEEN P1.DATE_BEGIN AND P1.DATE_END)  order by ord),0),
		PERC = ISNULL((SELECT TOP 1 P1.PERC FROM @PERIODY P1 WHERE I = 1 AND P1.PERC > 0 AND (P3.DATE_BEGIN BETWEEN P1.DATE_BEGIN AND P1.DATE_END) AND (P3.DATE_END BETWEEN P1.DATE_BEGIN AND P1.DATE_END) order by ord),0)
	FROM @PERIODY P3 
	WHERE P3.I = 3 
	
	--- 6. Соединение периодов
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, I, R, PERC)
	Select 
		MIN(DATE_BEGIN), MAX(DATE_END), 5, R, PERC
	FROM @PERIODY P4 
	WHERE P4.I = 4 
	GROUP BY YEAR(DATE_BEGIN), MONTH(DATE_BEGIN), R, PERC

	DECLARE @ARCHE_OPT13 INT --Не начисять суммы за счёт ФСС 
	SET @ARCHE_OPT13 = dbo.SA_GET_OPTION_BY_CODE('ARCHE_OPT13')
	IF @ARCHE_OPT13 = 1
		DELETE FROM @PERIODY WHERE I = 5 AND R = 0
	
	--== ПОЛУЧЕНИЕ ПЕРИОДОВ ЗАВЕРШЕНО!
	
	---Определение предела
	DECLARE @RAION NUMERIC(18,2)
	exec dbo.SA_EMPL_RAION_KOEF_BL @RAION OUT, @LINK_EMPL, @DATE_BEGIN
	
	SET @RAION = CASE WHEN ISNULL(@RAION,0) <1 THEN 1 ELSE ISNULL(@RAION,0) END
	
	DECLARE @SUM_LIMIT NUMERIC(18,4), @MINROT NUMERIC(18,2)
	SET @MINROT = dbo.minrot2(@DATE_BEGIN) * @EmplNumStake * @RAION 
	-- увеличенный на размер районного коэффициента
	--Сумма МРОТ должна быть в пределах количества ставок, т.к. по ней идет расчет за полностью отработанное время на полной ставке

--	SET @SUM_LIMIT = CASE @LIMIT
--				WHEN 2 THEN @MINROT -- в размере 1 МРОТ
--				WHEN 3 THEN 
--					CASE WHEN @DATE_BEGIN <= '20091231' THEN 	
--						(CASE WHEN @dekret = 0 THEN dbo.sa_get_option_by_code('ARCHE_OPT1') ELSE dbo.sa_get_option_by_code('ARCHE_OPT6') END) * @RAION 
--					ELSE	
--						-- !!! С 1 января 2010 года максимальный размер пособия одинаковый по все территории РФ!!!: Максимум без учета районныйх, но с учетом стажа
--						(CASE WHEN @dekret = 0 THEN dbo.sa_get_option_by_code('ARCHE_OPT1') * @RercStag/100 ELSE dbo.sa_get_option_by_code('ARCHE_OPT6') END) 
--					END
--				ELSE 0
--			END 
	----
	UPDATE @PERIODY
	SET 	DH = CASE WHEN @ARCHE_OPT2 = 1 THEN
			CASE WHEN @SystPay = 1 THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAY_DH(@LINK_EMPL,DATE_BEGIN,DATE_END)),0)
			ELSE ISNULL(CONVERT(NUMERIC(10,2),dbo.NORM_HOUR_DH(@LINK_EMPL,DATE_BEGIN,DATE_END)),0) END
			ELSE
				DATEDIFF(DAY,DATE_BEGIN, DATE_END)+1
			END,
		DH_NORM = CASE WHEN @ARCHE_OPT2 = 1 THEN
				CASE WHEN @SystPay = 1 THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL,MONTH(DATE_BEGIN),YEAR(DATE_BEGIN))),0)
				ELSE ISNULL(CONVERT(NUMERIC(10,2),dbo.NORM_HOURS(@LINK_EMPL,MONTH(DATE_BEGIN),YEAR(DATE_BEGIN))),0) END	
			ELSE
				--CASE WHEN @DATE_BEGIN <= '20091231' OR @LIMIT = 2 THEN
				CASE WHEN DATE_BEGIN <= '20091231' OR @LIMIT = 2 THEN
					DAY(dbo.DateEndOfMonth(DATE_BEGIN))
				ELSE
					30.4 --365.00/12	-- 30.4
				END
			END,
		SUM_LIMIT = 
			CONVERT(NUMERIC(18,2),
				CASE @LIMIT
					WHEN 2 THEN @MINROT -- в размере 1 МРОТ
					WHEN 3 THEN 
						CASE WHEN DATE_BEGIN <= '20091231' THEN 	
							(CASE WHEN @dekret = 0 THEN dbo.sa_get_option_by_code('ARCHE_OPT7') ELSE dbo.sa_get_option_by_code('ARCHE_OPT8') END) * @RAION 
						ELSE	
							-- !!! С 1 января 2010 года максимальный размер пособия одинаковый по все территории РФ!!!: Максимум без учета районныйх, но с учетом стажа
	--						(CASE WHEN @dekret = 0 THEN dbo.sa_get_option_by_code('ARCHE_OPT1') * @RercStag/100 ELSE dbo.sa_get_option_by_code('ARCHE_OPT6') END) 
							(CASE WHEN @dekret = 0 THEN dbo.sa_get_option_by_code('ARCHE_OPT1') ELSE dbo.sa_get_option_by_code('ARCHE_OPT6') END) 
						END
					ELSE 0
				END
			)	
	WHERE I = 5

	---------------------------------------------------------------------------------------
	--Откорректируем оплачиваемые дни за каждый период
	DECLARE @Cur3 CURSOR
	Declare @NEXT_DATE DATETIME

	IF @ARCHE_OPT9 = 1
	BEGIN
		SET @Cur3 = CURSOR FORWARD_ONLY

		FOR SELECT DATE_BEGIN FROM @PERIODY WHERE I = 5 AND YEAR(@DATE_DOC) BETWEEN YEAR(DATE_BEGIN) AND YEAR(DATE_END) ORDER BY DATE_BEGIN
		
		OPEN @Cur3
		FETCH NEXT FROM @Cur3 INTO @NEXT_DATE
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN

				UPDATE @PERIODY
				SET DH = (CASE WHEN DH < @MAX_DAYS_IVENT THEN DH ELSE @MAX_DAYS_IVENT END)
				WHERE I = 5 AND DATE_BEGIN = @NEXT_DATE
				
				SELECT @MAX_DAYS_IVENT = (CASE WHEN DH < @MAX_DAYS_IVENT THEN @MAX_DAYS_IVENT - DH ELSE 0 END)
				FROM @PERIODY
				WHERE I = 5 AND DATE_BEGIN = @NEXT_DATE

			END
		
			FETCH NEXT FROM @Cur3 INTO @NEXT_DATE
		END
		
		CLOSE @Cur3
		DEALLOCATE @Cur3
	END	
	---------------------------------------------------------------------------------------

	---
	DECLARE @REP_SUMMA_PR NUMERIC(18,2), @SUMMA_ZP NUMERIC(18,2), @SUMMA_PR NUMERIC(18,2), @NORM NUMERIC(18,2), @WORK NUMERIC(18,2), @SR_ZP NUMERIC(20,4)
	
	--- Время за расчетный период
	SELECT  [PERIOD],
		[NORM] = MAX(CASE WHEN @SystPay = 1 OR @ARCHE_OPT2 = 2 THEN DAYS_N ELSE  HOURS_N END),
		[WORK] = MAX(CASE WHEN @SystPay = 1 OR @ARCHE_OPT2 = 2 THEN DAYS ELSE HOURS END) 	
	INTO #TMP
	FROM dbo.SDOC_ADIS_TABLE2 WHERE LINK_UP = @LINK_DOC
	GROUP BY [PERIOD]

	SELECT  @NORM = SUM([NORM]), @WORK = SUM([WORK]) FROM #TMP

	---	
	SELECT 
		@SUMMA_ZP = ISNULL(SUM(SUMMA),0), 
		@SUMMA_PR = ISNULL( CONVERT(NUMERIC(18,2), SUM(SUMMA_PREM) * CASE WHEN @ARCHE_OPT2 = 1 AND @NORM <> 0 THEN @WORK / @NORM ELSE 1 END ),0),
		@REP_SUMMA_PR = SUM(SUMMA_PREM)
	FROM dbo.SDOC_ADIS_TABLE2 WHERE LINK_UP = @LINK_DOC

	---	
	SET @SR_ZP = CONVERT(NUMERIC(18,2),(CASE WHEN ISNULL(@WORK,0) <> 0 THEN ISNULL((@SUMMA_ZP + @SUMMA_PR),0) / @WORK else 0 end))

	----	
	DECLARE @KBK_KOEF TABLE (LINK_KBK INT, KOEF NUMERIC(18,4))
	DECLARE @SR_ZP_MINI numeric(20,4), @SR_ZP_R numeric(20,4)

	SET @SR_ZP_R = @SR_ZP
	
	--- Если у сотрудника не было заработка и нет установленных постоянных начислений, то расчет исходя из минрот

	IF (CASE WHEN @ARCHE_OPT2 = 1	
		THEN 
			CASE WHEN @SystPay = 1 
				THEN	ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL, MONTH(@DATE_BEGIN), YEAR(@DATE_BEGIN) )),0)
				ELSE	ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_HOURS(@LINK_EMPL, MONTH(@DATE_BEGIN), YEAR(@DATE_BEGIN) )),0) 
			END
		ELSE DATEDIFF(DAY,dbo.DateBeginOfMonth(@DATE_BEGIN), dbo.DateEndOfMonth(@DATE_BEGIN))+1 
	END) > 0
		SET @SR_ZP_MINI = 
			@MINROT / (CASE WHEN @ARCHE_OPT2 = 1 
					THEN 
						(CASE WHEN @SystPay = 1 
							THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL, MONTH(@DATE_BEGIN), YEAR(@DATE_BEGIN) )),0) 
							ELSE ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_HOURS(@LINK_EMPL, MONTH(@DATE_BEGIN), YEAR(@DATE_BEGIN) )),0) 	
						END)
					ELSE DATEDIFF(DAY,dbo.DateBeginOfMonth(@DATE_BEGIN), dbo.DateEndOfMonth(@DATE_BEGIN))+1 
				END)
	ELSE
		SET @SR_ZP_MINI = 0


--	IF ISNULL(@SR_ZP,0) <= ISNULL(@SR_ZP_MINI,0) OR ISNULL(@SR_ZP,0) = 0  BEGIN
	IF ISNULL(@SR_ZP,0) = 0  BEGIN
		DELETE FROM @KBK_KOEF
		INSERT INTO @KBK_KOEF (LINK_KBK, KOEF) 
		SELECT LINK_KBK, 1 FROM dbo.ku_emplstafkbk(default) WHERE LINK_EMPL = @LINK_EMPL
	END 
	ELSE BEGIN
		---
		DECLARE @S NUMERIC(18,2)
		SET @S = ISNULL((SELECT SUM(SUMMA) + SUM(SUMMA_PREM) FROM dbo.SDOC_ADIS_TABLE2 WHERE LINK_UP = @LINK_DOC),0)


		INSERT INTO @KBK_KOEF (LINK_KBK, KOEF) 
		SELECT LINK_KBK, CASE WHEN @S <> 0 THEN (SUM(SUMMA)+SUM(SUMMA_PREM)) / @S ELSE 0 END 
		FROM dbo.SDOC_ADIS_TABLE2  WHERE LINK_UP = @LINK_DOC 
		GROUP BY LINK_KBK
	END
	---
	DELETE FROM dbo.SDOC_ADIS_TABLE1  WHERE LINK_UP = @LINK_DOC
	INSERT INTO dbo.SDOC_ADIS_TABLE1 (LINK_UP, ORDERS, DATE1, DATE2, SUM_LIMIT, [DAYS], [HOURS], SR_ZP, SUMMA, PERC, PAYER, LINK_KBK, KOEF_KBK)
	SELECT @LINK_DOC, 0, DATE_BEGIN, DATE_END, 
		LIMIT = CONVERT(NUMERIC(20,4), (CASE WHEN @LIMIT = 2 THEN dbo.minrot2(DATE_BEGIN) * @RAION ELSE P.SUM_LIMIT END) / DH_NORM),
		(CASE WHEN @SystPay = 1 OR @ARCHE_OPT2 = 2 THEN DH ELSE 0 END),
		(CASE WHEN @SystPay = 1 OR @ARCHE_OPT2 = 2 THEN 0 ELSE DH END),
		SR_ZP = NULL,
		0,
		PERC,
		R,
		K.LINK_KBK,
		K.KOEF
	FROM @PERIODY P INNER JOIN @KBK_KOEF K ON 1=1
	WHERE I = 5
	ORDER BY DATE_BEGIN

	UPDATE sdoc_adis WITH (ROWLOCK) 
	SET 	LINK_EMPL = @LINK_EMPL, LINK_PAY=@LINK_PAYS, DATE_BEGIN=@DATE_BEGIN_RP, SR_ZAR=@SR_ZP_R, SR_PREM=@SUMMA_PR, TYP_PERIOD=@TYP_PERIOD, LIMIT=@LIMIT, REF_DOC=@LINK_ARCH, INSTRUCT = 1
	WHERE LINK_UP = @LINK_DOC
	
END --@RECALC <= 2 

UPDATE dbo.SDOC_ADIS_TABLE1
SET 
	SR_ZP = convert(numeric(20,4),(CASE WHEN SR_ZAR < SUM_LIMIT OR @LIMIT = 4 AND @LIMIT <> 2 THEN SR_ZAR ELSE SUM_LIMIT END))
			* convert(numeric(20,4),(CASE WHEN PERC > 0 then PERC/100 else 0 end))
FROM 
	dbo.sdoc_adis A 
	INNER JOIN dbo.SDOC_ADIS_TABLE1 T ON A.LINK_UP = T.LINK_UP
WHERE 
	T.LINK_UP = @LINK_DOC AND KOEF_KBK IS NOT NULL

--Заменяю источник финансирования за счет ФСС
UPDATE dbo.SDOC_ADIS_TABLE1
SET 
	LINK_KBK = SF.[LINK_SS_SFIN]
FROM 
	dbo.sdoc_adis A 
	INNER JOIN dbo.SDOC_ADIS_TABLE1 T ON A.LINK_UP = T.LINK_UP
	INNER JOIN dbo.SAL_SFIN SF ON SF.LINK = T.LINK_KBK
WHERE 
	T.LINK_UP = @LINK_DOC AND PAYER = 0 AND SF.[LINK_SS_SFIN] IS NOT NULL

----
Select CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR, DAYS = SUM(CJ.DAYS), HOURS = SUM(CJ.HOURS), LINK_EKR, SUMMA = SUM(SUMMA)
INTO #SUM_OLD
from 
	dbo.SDOC_ADIS SA inner join dbo.CALCULATE_JURNAL CJ on CJ.LINK_DOC = SA.LINK_UP
	inner join dbo.sdoc d on CJ.LINK_DOC = d.link 
where
	ISNULL(@LINK_ARCH,0) > 0
	AND
	SA.REF_DOC = @LINK_ARCH
	and
	d.object = (Select top 1 link from s_objects where code = 'DOCUMENTS_ADD_ARCHE')
GROUP BY
	CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR, LINK_EKR

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

---- сопоставить старые
UPDATE dbo.SDOC_ADIS_TABLE1
SET 
	SUMMA_NEW = CONVERT(NUMERIC(18,2), T.SR_ZP * (CASE WHEN @SystPay = 1 OR @ARCHE_OPT2 = 2 THEN T.DAYS ELSE T.HOURS END) * KOEF_KBK),
	SUMMA_OLD = ISNULL(SO.SUMMA,0),
	DAYS = COALESCE(T.DAYS,0) - COALESCE(SO.DAYS,0), 
	HOURS = COALESCE(T.HOURS,0) - COALESCE(SO.HOURS,0)	
FROM 
	dbo.sdoc_adis A 
	INNER JOIN dbo.SDOC_ADIS_TABLE1 T ON A.LINK_UP = T.LINK_UP
	LEFT JOIN #SUM_OLD SO ON T.DATE1 = SO.DATE_BEGIN AND T.DATE2 = SO.DATE_END AND T.LINK_KBK = SO.LINK_VKR and PAYER = (CASE WHEN LINK_EKR=@LInkEKR213 then 0 else 1 end)
WHERE 
	T.LINK_UP = @LINK_DOC AND KOEF_KBK IS NOT NULL AND SR_ZP IS NOT NULL

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

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

--DELETE FROM dbo.SDOC_ADIS_TABLE1
--WHERE LINK_UP = @LINK_DOC AND SUMMA = 0

SET @I = 0
UPDATE dbo.SDOC_ADIS_TABLE1  

SET @I = @I+1, ORDERS = @I
WHERE LINK_UP = @LINK_DOC

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

---
SELECT @NUMBER = NUMBER,  @DATE_DOC = DATE from SDOC WHERE LINK = @LINK_DOC

if exists (select * from #SUM_OLD)
	set @comment = 'Перерасчет: ' + @comment

--- Сохрание расчета
SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = 'DOCUMENTS_ADD_ARCHE'
EXECUTE dbo.SALARY_UPD_SDOC @LINK_DOC OUTPUT, @varKSsoLink, @NUMBER,@DATE_DOC,@comment,0,null,@SUMMA

IF @OPER = 1 
	exec dbo.SD_N_BOL_PROV @LINK_DOC

SET NOCOUNT OFF


GO


GRANT EXECUTE ON dbo.[SA_N_BOL_FILL1] TO PUBLIC

GO

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

GO

CREATE   PROCEDURE dbo.SD_O_OTHER_FILL
@LINK INT
AS  

DECLARE @Month int, 
		@Year int, 
		@Link1 int,
		@DEP_LINK INT,
		@Date DATETIME	

SELECT 
	@Year = YEAR(S.DATE_CALC),
	@Month = MONTH(S.DATE_CALC),
	@DEP_LINK = S.LINK_DEP,
	@Date = dbo.DATEENDOFMONTH(S.DATE_CALC)
FROM 
	dbo.SDOC S
WHERE 
	S.LINK = @LINK

IF @DEP_LINK IS NULL
	Set @DEP_LINK = Coalesce( (SELECT TOP 1 ZB_LINK FROM dbo.KS_OPTIONS_ZB), dbo.GetOwnDepLink())

---Справочник тарифов
--!!! Ставки берет от тарифа Общий и не учитывает шкалу. При необходимости требуется переделать
CREATE TABLE #RANGE(LINK_PAYS INT, PREDEL NUMERIC(18,2), [PERCENT] NUMERIC(18,2))
INSERT INTO #RANGE (LINK_PAYS, PREDEL,  [PERCENT])
SELECT 
	DR.LINK_PAYS, PREDEL, [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] <= @Date ORDER BY [DATE] DESC) 	

DECLARE @COLUMN_REF_PAY_MROT_T3 INT
SET @COLUMN_REF_PAY_MROT_T3 = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'COLUMN_REF_PAY_MROT_T3')

----Инвалиды и процент по ним
CREATE TABLE #INV ([PERCENT] NUMERIC(18,2), LINK INT)
INSERT  INTO #INV ([PERCENT], LINK)
SELECT
	[PERCENT] = MP.summa, I.PERS_LINK
FROM	
	dbo.MINROT_PAYS MP
	INNER JOIN dbo.PERS_INVALID I ON 1=1
WHERE
	[OBJECT] = @COLUMN_REF_PAY_MROT_T3
	AND
	LINK_MINROT = (SELECT TOP 1 LINK FROM MINROT WHERE PERIOD<=@Date ORDER BY PERIOD DESC)
	AND
	dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@Month,@Year))
		BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')	

--===РАСЧЁТ СКИДКИ
--Информация о предельном размере скидки
CREATE TABLE #SKIDKA (LINK_INC INT, PREDEL NUMERIC(18,2))
INSERT INTO #SKIDKA (LINK_INC, PREDEL)
SELECT TI.LINK, D.PREDEL
FROM 
	dbo.Salary_deduct_esn(@Date) D	
	INNER JOIN dbo.DICTIONARY_TYP_INCOMS TI ON TI.REF_DEDUCT = D.REF_PAY
	AND dbo.SA_GET_OPTION_BY_CODE('ESNTR_OPTIONS_OPT3') = 1 -- Предоставлять скидки 
	
--База расчёта
CREATE TABLE #BASE (LINK_TAX INT, LINK_PAY INT)
INSERT INTO #BASE (LINK_TAX, LINK_PAY)
SELECT T.LINK_TAX, T.LINK_PAYS 
FROM
	dbo.PAYS P  
	INNER JOIN dbo.TAX_REF T ON T.LINK_TAX = P.LINK
WHERE
	P.[OBJECT] = 3 AND P.WAY_CALC = 5	

--Базовые суммы по физлицам в разрезе кодов дохода и источников
DECLARE @LINK_EKR211 INT, @LINK_EKR212 INT, @LINK_EKR213 INT
SET @LINK_EKR211 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '211')
SET @LINK_EKR212 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '212')
SET @LINK_EKR213 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')

DECLARE @SALARY_PROV_OPT4 TINYINT
SET @SALARY_PROV_OPT4 = dbo.sa_get_option_by_code('SALARY_PROV_OPT4')

CREATE TABLE #SUMMA (LINK_TAX INT, LINK_PERS INT, LINK_INC INT, LINK_VKR INT, LINK_EKR INT, SUMMA_M NUMERIC(18,2),SUMMA NUMERIC(18,2), LINK_VKR2 INT)
INSERT INTO #SUMMA (LINK_TAX, LINK_PERS, LINK_INC, LINK_VKR, LINK_EKR, SUMMA_M, SUMMA, LINK_VKR2)
SELECT
	B.LINK_TAX,
	ISNULL(J.PERS_LINK,E.PERS_LINK),
	P.LINK_INC,
	LINK_VKR = ISNULL(SF.LINK_SS_SFIN,J.LINK_VKR),
	CASE WHEN @SALARY_PROV_OPT4 = 0 THEN 
		CASE WHEN COALESCE(J.LINK_EKR,@LINK_EKR213) = @LINK_EKR211 THEN @LINK_EKR213 ELSE COALESCE(J.LINK_EKR,@LINK_EKR213) END
	ELSE 
		CASE WHEN COALESCE(J.LINK_EKR,@LINK_EKR213) IN (@LINK_EKR211, @LINK_EKR212) THEN @LINK_EKR213 ELSE COALESCE(J.LINK_EKR,@LINK_EKR213) END				
	END,	
	SUMMA_M = SUM(CASE WHEN MONTH(J.PERIOD_BEGIN) = @Month THEN SUMMA ELSE 0 END),
	SUMMA  = SUM(SUMMA),
	LINK_VKR2 = J.LINK_VKR
FROM
	#BASE B 
	INNER JOIN dbo.PAYS P ON P.LINK = B.LINK_PAY
	INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_PAYS = P.LINK
	INNER JOIN dbo.EMPL E ON E.LINK = J.LINK_EMPL
	INNER JOIN dbo.SAL_SFIN SF ON SF.LINK = J.LINK_VKR
WHERE
	J.LINK_DEP = @DEP_LINK
	AND
	P.[OBJECT] = 1 
	AND
	YEAR(J.PERIOD_BEGIN) = @Year AND MONTH(J.PERIOD_BEGIN) <= @Month
	--AND
	--J.LINK_EKR <> @LINK_EKR213
GROUP BY
	B.LINK_TAX, ISNULL(J.PERS_LINK,E.PERS_LINK), P.LINK_INC, LINK_VKR, J.LINK_EKR, SF.LINK_SS_SFIN

		
-- Базовые суммы по физлицам в разрезе кодов дохода
CREATE TABLE #SUMMA2 (LINK_TAX INT, LINK_PERS INT, LINK_INC INT, SUMMA_M NUMERIC(18,2), SUMMA NUMERIC(18,2))
INSERT INTO #SUMMA2 (LINK_TAX, LINK_PERS, LINK_INC, SUMMA_M, SUMMA)
SELECT LINK_TAX, LINK_PERS, LINK_INC, SUM(SUMMA_M), SUM(SUMMA)
FROM #SUMMA
GROUP BY LINK_TAX, LINK_PERS, LINK_INC


--Удалить рассчитанную скидку по данному расчёту, чтобы рассчитать её заново
DELETE FROM dbo.SDOC_DOT_SKIDKI WHERE LINK_UP = @LINK

-- Размер уже предоставленной скидки с начала года в разрезе кодов дохода
CREATE TABLE #SKIDKA_PREV (LINK_TAX INT, LINK_PERS INT, LINK_INC INT, SUMMA NUMERIC(18,2))

INSERT INTO #SKIDKA_PREV (LINK_TAX, LINK_PERS, LINK_INC, SUMMA)
SELECT LINK_TAX, LINK_PERS, LINK_INC, SUM(SUMMA)
FROM 
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DOT_SKIDKI S ON S.LINK_UP = D.LINK
WHERE
	D.LINK_DEP = @DEP_LINK
	AND 
	YEAR(DATE_CALC)	= @Year AND MONTH(DATE_CALC) < @Month
GROUP BY
	LINK_TAX, LINK_PERS, LINK_INC

--
DECLARE @ESNTR_OPTIONS_OPT5 INT
SET @ESNTR_OPTIONS_OPT5 = dbo.SA_GET_OPTION_BY_CODE('ESNTR_OPTIONS_OPT5')

--Предоставленные скидки с предыдущего места работы
CREATE TABLE #PREV_DED (LINK_PERS INT, LINK_INC INT, SUMMA NUMERIC(18,2))
--
INSERT INTO #PREV_DED (LINK_PERS, LINK_INC, SUMMA)
SELECT E.PERS_LINK, LINK_INC = T.LINK, SUMMA = SUM(PD.SUMMA_DED)
FROM 
	dbo.SD_EMPL_PREV_DED PD
	INNER JOIN dbo.DICTIONARY_TYP_INCOMS T with (nolock) ON T.REF_DEDUCT = PD.LINK_DED
	INNER JOIN dbo.EMPL E with (nolock) ON E.LINK = PD.LINK_EMPL
	INNER JOIN dbo.ITEM_MOVE IM with (nolock) ON IM.EMPL_LINK = E.LINK AND IM.ACTIVE = 1 AND IM.NEW_FACE=1 AND IM.[STATUS] IN (1,3) AND IM.DATE_BEGIN <= @Date
	INNER JOIN (
		SELECT E.PERS_LINK, MAX(DATE_BEGIN) AS DATE_BEGIN
		FROM 
			dbo.EMPL E with (nolock)
			INNER JOIN dbo.ITEM_MOVE IM with (nolock) ON IM.EMPL_LINK = E.LINK AND IM.ACTIVE = 1 AND IM.NEW_FACE=1 AND IM.[STATUS] IN (1,3) AND IM.DATE_BEGIN <= @Date
			LEFT JOIN DBO.ITEM_DIS_FACE IDF with (nolock) ON IDF.EMPL_LINK = E.LINK AND IDF.ACTIVE=1 AND COALESCE(IDF.DIS_DATE,'20990101') >= dbo.DateBeginOfMonth(@Date)	
		GROUP BY
			E.PERS_LINK	
	) A ON A.PERS_LINK = E.PERS_LINK AND A.DATE_BEGIN = IM.DATE_BEGIN
WHERE
	E.DEP_LINK = @DEP_LINK
	AND
	YEAR(IM.DATE_begin) = @Year --YEAR(dbo.kd_DateBeginWork(@linkEmpl,null)) = @Year
	AND
	@ESNTR_OPTIONS_OPT5 = 1 --Учитывать вычеты, предоставленные на предыдущем месте работы
GROUP BY
	E.PERS_LINK, T.LINK
	
-- Расчёт скидки за месяц по физлицам в разрезе кодов дохода и источников
INSERT INTO dbo.SDOC_DOT_SKIDKI (LINK_UP, LINK_TAX, LINK_PERS, LINK_INC, LINK_VKR, LINK_EKR, SUMMA, [PERCENT])
SELECT 
	@LINK, S2.LINK_TAX, S2.LINK_PERS, S2.LINK_INC, S.LINK_VKR, S.LINK_EKR,
	--Остаток скидки в пределах месячного дохода
	--CASE WHEN S2.SUMMA_M > CASE WHEN ISNULL(SP.SUMMA,0) < SK.PREDEL THEN (SK.PREDEL - ISNULL(SP.SUMMA,0)) * (S.SUMMA_M / S2.SUMMA_M) ELSE 0 END
	--	THEN CASE WHEN ISNULL(SP.SUMMA,0) < SK.PREDEL THEN (SK.PREDEL - ISNULL(SP.SUMMA,0)) * (S.SUMMA_M / S2.SUMMA_M) ELSE 0 END
	--	ELSE S2.SUMMA_M
	--END,
	(
		CASE WHEN
			--Всего надо скидку
			(CASE WHEN ISNULL(PD.SUMMA,0) + ISNULL(S2.SUMMA,0) > ISNULL(SK.PREDEL,0) THEN ISNULL(SK.PREDEL,0) ELSE ISNULL(PD.SUMMA,0) + ISNULL(S2.SUMMA,0) END) > 0 
		THEN
		(
			--Всего надо скидку
			(CASE WHEN ISNULL(PD.SUMMA,0) + ISNULL(S2.SUMMA,0) > ISNULL(SK.PREDEL,0) THEN ISNULL(SK.PREDEL,0) ELSE ISNULL(PD.SUMMA,0) + ISNULL(S2.SUMMA,0) END) 
			--Уже предоставили
			- ISNULL(SP.SUMMA,0) - ISNULL(PD.SUMMA,0)
		)	
			----пропорционально кодам доходов
			* (S.SUMMA_M / S2.SUMMA_M)
		ELSE
		0 
		END	
	),
	[PERCENT] = ISNULL(I.[PERCENT],DR.[PERCENT])
FROM 
	#RANGE DR --Ставка налога
	INNER JOIN #SUMMA2 S2 ON -- Базовые суммы по физлицам в разрезе кодов дохода
							S2.LINK_TAX = DR.LINK_PAYS
	INNER JOIN #SUMMA S ON --Базовые суммы по физлицам в разрезе кодов дохода и источников
							S.LINK_TAX = S2.LINK_TAX AND S.LINK_PERS = S2.LINK_PERS AND S.LINK_INC = S2.LINK_INC
	INNER JOIN #SKIDKA SK ON --Информация о предельном размере скидки
							SK.LINK_INC = S.LINK_INC
	LEFT JOIN #SKIDKA_PREV SP ON -- Размер уже предоставленной скидки с начала года в разрезе кодов дохода
							SP.LINK_TAX = S2.LINK_TAX AND SP.LINK_PERS = S2.LINK_PERS AND SP.LINK_INC = S2.LINK_INC
	LEFT JOIN #PREV_DED PD ON --Предоставленные скидки с предыдущего места работы
						PD.LINK_PERS = S2.LINK_PERS AND PD.LINK_INC = S2.LINK_INC								
	LEFT JOIN #INV I ON --Инвалиды и процент по ним
						I.LINK = S2.LINK_PERS
WHERE
	S2.SUMMA_M <> 0
	

--===РАСЧЁТ ВЫЧЕТОВ
--Информация о предельном размере ВЫЧЕТА
CREATE TABLE #VYCHET (LINK_DED INT, PREDEL NUMERIC(18,2))
INSERT INTO #VYCHET (LINK_DED, PREDEL)
SELECT TI.LINK, D.PREDEL
FROM 
	dbo.Salary_deduct_esn(@Date) D	
	INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION TI ON TI.LINK = D.REF_PAY
	LEFT JOIN dbo.DICTIONARY_TYP_INCOMS TI2 ON TI2.REF_DEDUCT = D.REF_PAY
WHERE 
	TI2.REF_DEDUCT IS NULL
	AND
	dbo.SA_GET_OPTION_BY_CODE('ESNTR_OPTIONS_OPT4') = 1 -- Предоставлять вычеты		
	
--Определение размера удержаний, дающие права на предоставление вычетов
CREATE TABLE #SUMMA_U (LINK_DED INT, LINK_PERS INT, SUMMA_M NUMERIC(18,2), SUMMA NUMERIC(18,2))
INSERT INTO #SUMMA_U (LINK_DED, LINK_PERS, SUMMA_M, SUMMA)
---Вычеты от удержаний
SELECT 
	TA.LINK_DED, ISNULL(J.PERS_LINK,E.PERS_LINK), 
	SUMMA_M = SUM(CASE WHEN MONTH(J.PERIOD_BEGIN) = @Month THEN SUMMA ELSE 0 END),
	SUMMA  = SUM(SUMMA)
FROM 
	dbo.EMPL E inner join dbo.calculate_jurnal J ON e.link = J.link_empl
	inner join dbo.TAX2_APP TA ON TA.LINK_UP = J.LINK_PAYS
WHERE 
	J.LINK_DEP = @DEP_LINK
	AND YEAR(J.PERIOD_BEGIN) = @Year AND MONTH(J.PERIOD_BEGIN) <= @Month
	AND ISNULL(TA.LINK_DED,0) > 0
GROUP BY 
	TA.LINK_DED, ISNULL(J.PERS_LINK,E.PERS_LINK)

--Удалить рассчитанную скидку по данному расчёту, чтобы рассчитать её заново
DELETE FROM dbo.SDOC_DOT_VYCHET WHERE LINK_UP = @LINK	

-- Размер уже предоставленного вычета с начала года в разрезе кодов вычетов
CREATE TABLE #VYCHET_PREV (LINK_TAX INT, LINK_PERS INT, LINK_DED INT, SUMMA NUMERIC(18,2))

INSERT INTO #VYCHET_PREV (LINK_TAX, LINK_PERS, LINK_DED, SUMMA)
SELECT LINK_TAX, LINK_PERS, LINK_DED, SUM(SUMMA)
FROM 
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DOT_VYCHET S ON S.LINK_UP = D.LINK
WHERE
	D.LINK_DEP = @DEP_LINK
	AND 
	YEAR(DATE_CALC)	= @Year AND MONTH(DATE_CALC) < @Month
GROUP BY
	LINK_TAX, LINK_PERS, LINK_DED

--==== Расчёт ВЫЧЕТА за месяц по физлицам в разрезе кодов дохода и источников

--Вычеты по сотрудникам в разрезе кодов вычетов
SELECT 
	LINK_TAX = P.LINK, S.LINK_PERS, S.LINK_DED,
	SUMMA_M = 
	--CASE WHEN S.SUMMA_M > CASE WHEN ISNULL(VP.SUMMA,0) < V.PREDEL THEN (V.PREDEL - ISNULL(VP.SUMMA,0)) * (S.SUMMA_M / S.SUMMA_M) ELSE 0 END
	--	THEN CASE WHEN ISNULL(VP.SUMMA,0) < V.PREDEL THEN (V.PREDEL - ISNULL(VP.SUMMA,0)) * (S.SUMMA_M / S.SUMMA_M) ELSE 0 END
	--	ELSE S.SUMMA_M
	--END,
	(
		--Всего надо скидку
		(CASE WHEN ISNULL(S.SUMMA,0) > ISNULL(V.PREDEL,0) THEN ISNULL(V.PREDEL,0) ELSE ISNULL(S.SUMMA,0) END) 
		--Уже предоставили
		- ISNULL(VP.SUMMA,0)
	),		
	[PERCENT] = ISNULL(I.[PERCENT],DR.[PERCENT])
INTO #TMP_VYCH
FROM
	dbo.PAYS P
	INNER JOIN #RANGE DR --Ставка налога
							ON P.LINK = DR.LINK_PAYS
	INNER JOIN #SUMMA_U S -- Вычеты по физлицам
							ON 1=1
	INNER JOIN #VYCHET V --Информация о предельном размере скидки
						ON V.LINK_DED = S.LINK_DED
	LEFT JOIN #VYCHET_PREV VP -- Размер уже предоставленного вычета с начала года
						ON VP.LINK_PERS = S.LINK_PERS AND VP.LINK_DED = S.LINK_DED
	LEFT JOIN #INV I --Инвалиды и процент по ним
					ON I.LINK = S.LINK_PERS
WHERE
	P.[OBJECT] = 3 AND P.WAY_CALC = 5
	AND S.SUMMA_M <> 0

--Доход по сотрудникам в разрезе источников
SELECT LINK_TAX, LINK_PERS, LINK_VKR, LINK_VKR2, LINK_EKR, SUMMA_M = SUM(SUMMA_M)
INTO #TMP_DOH FROM #SUMMA GROUP BY LINK_TAX, LINK_PERS, LINK_VKR, LINK_EKR, LINK_VKR2

--Доход по сотрудникам
SELECT LINK_TAX, LINK_PERS, SUMMA_M = SUM(SUMMA_M)
INTO #TMP_DOH2 FROM #SUMMA GROUP BY LINK_TAX, LINK_PERS

--Вычеты по сотрудникам в разрезе источников и кодов вычетов
INSERT INTO dbo.SDOC_DOT_VYCHET (LINK_UP, LINK_TAX, LINK_PERS, LINK_VKR, LINK_EKR, LINK_DED, SUMMA, [PERCENT])
SELECT 
	@LINK, D2.LINK_TAX, D2.LINK_PERS, D.LINK_VKR, D.LINK_EKR, V.LINK_DED, ISNULL(V.SUMMA_M,0) * ISNULL(D.SUMMA_M,0) / D2.SUMMA_M, V.[PERCENT]
FROM
	#TMP_DOH2 D2 
	INNER JOIN #TMP_DOH D ON D.LINK_TAX = D2.LINK_TAX AND D.LINK_PERS = D2.LINK_PERS
	INNER JOIN #TMP_VYCH V ON D2.LINK_TAX = V.LINK_TAX AND D2.LINK_PERS = V.LINK_PERS
WHERE
	ISNULL(D2.SUMMA_M,0) <> 0	

SELECT 
	[PERCENT] = ISNULL(I.[PERCENT],DR.[PERCENT]),
	DR.LINK_PAYS,
	CODE_PAYS = P.CODE,
	NAME_PAYS = P.NAME,
	S.LINK_VKR,
	[NAME_VKR] = F.CODE,
	S.LINK_EKR,
	[NAME_EKR] = G.CODE,	
	SUMMA = SUM(S.SUMMA_M),
	SKIDKA = SUM(ISNULL(SK.SUMMA,0)),
	VYCHET = SUM(ISNULL(V.SUMMA,0)),
	S.LINK_VKR2,
	[NAME_VKR2] = F2.CODE	
FROM 
	#RANGE DR
	INNER JOIN dbo.PAYS P ON P.LINK = DR.LINK_PAYS
	INNER JOIN #TMP_DOH S ON S.LINK_TAX = DR.LINK_PAYS
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = S.LINK_VKR
	INNER JOIN dbo.SAL_SFIN F2 ON F2.LINK = S.LINK_VKR2
	INNER JOIN dbo.KOSGU G ON G.LINK = S.LINK_EKR
	LEFT JOIN dbo.SDOC_DOT_SKIDKI SK ON  SK.LINK_UP = @LINK AND SK.LINK_TAX = DR.LINK_PAYS AND SK.LINK_PERS = S.LINK_PERS AND SK.LINK_VKR = S.LINK_VKR and SK.LINK_EKR = S.LINK_EKR
	LEFT JOIN 
	(
		SELECT LINK_TAX, LINK_PERS, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM dbo.SDOC_DOT_VYCHET 
		WHERE LINK_UP = @LINK GROUP BY LINK_TAX, LINK_PERS, LINK_VKR, LINK_EKR
	) V
	ON V.LINK_TAX = DR.LINK_PAYS AND V.LINK_PERS = S.LINK_PERS AND V.LINK_VKR = S.LINK_VKR AND V.LINK_EKR = S.LINK_EKR
	LEFT JOIN #INV I ON I.LINK = S.LINK_PERS
GROUP BY
	ISNULL(I.[PERCENT],DR.[PERCENT]),
	DR.LINK_PAYS,
	P.CODE,
	P.NAME,
	S.LINK_VKR,
	F.CODE,
	S.LINK_EKR,
	G.CODE,
	S.LINK_VKR2,
	F2.CODE

DROP TABLE #SKIDKA
DROP TABLE #BASE
DROP TABLE #SUMMA
DROP TABLE #SUMMA2
DROP TABLE #SKIDKA_PREV
DROP TABLE #INV
DROP TABLE #TMP_VYCH
DROP TABLE #TMP_DOH
DROP TABLE #RANGE

GO


GRANT EXECUTE ON dbo.[SD_O_OTHER_FILL] TO PUBLIC

GO


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

GO


CREATE PROCEDURE [dbo].SA_N_BOL_FILL2 
(
 @LINK_DOC INT OUTPUT, --Ссылка на документ.	
 @LINK_ARCH INT, --Ссылка на больничный
 @LINK_PAYS INT = NULL, --Ссылка на вид начисления
 @TYP_PERIOD TINYINT = 3, --Тип расчетного периода: 1- по текущему месяцу, 2- по двум предыдущим, 3- по 12 предудущим месяцам
 @LIMIT TINYINT = 3,--Тип предела: 1- 2 тарифа, 2- 1 МРОТ, 3- по установленному значению, 4 - без ограничений
 @RECALC TINYINT = 0, -- 0 Полный расчет. расчет начинается с таблицы 3 
			-- 1 - не надо рассчитывать по видам начислений
			-- 2 - не надо рассчитывать по месяцам
			-- 3 - не надо рассчитывать средние суммы
 @OPER TINYINT = 0, -- 1 - сформировать операции
 @LINK_DEP INT = NULL
)
AS

SET NOCOUNT ON

DECLARE
 @LINK_EMPL INT, --Ссылка на сотрудника
 @DATE_BEGIN DATETIME, --Начало больничного
 @DATE_BEGIN_P DATETIME, --Начало больничного
 @DATE_END DATETIME, --Окончание больничного
 @REF_TYP_ARHE INT, --Ссылка на вид больничного
 @STAGE_Y INT, --Стаж
 @STAGE_M INT, --Стаж
 @comment varchar(100),
 @extension_DIS int,
 @dekret tinyint
 
DECLARE @UNAME VARCHAR(30)
SET @UNAME = CASE WHEN DBO.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT10') = 1 THEN ISNULL(dbo.AdminGetUserFIO(default),'') ELSE '' END
SET @UNAME = @UNAME + CASE WHEN LEN(@UNAME) > 0 THEN ':' ELSE '' END

---инит
SELECT @LINK_EMPL = REF_EMPL, @LINK_PAYS = ISNULL(@LINK_PAYS,LINK_PAYS), @DATE_BEGIN = DATE1, @DATE_END = DATEADD(day,DAYS-1, DATE1),
	@REF_TYP_ARHE = REF_TYP_ARHE,  @STAGE_Y = NEPR_YEAR,  @STAGE_M = NEPR_MONTH,
	@comment = @UNAME + 'Начисление по Б/Л:' + ISNULL(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM([NAME_TYP_ARHE])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
	@extension_DIS = REF_DOC, @dekret = ISNULL(D.DEKRET,0),
	@LINK_DEP = ISNULL(@LINK_DEP,LINK_DEP)
FROM dbo.DIS D 
WHERE D.LINK = @LINK_ARCH

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

SET @TYP_PERIOD = 4 --За 2 года

-- Проверка на продолжение больничного листа
DECLARE @varKSRefDoc int
SET @varKSRefDoc = ISNULL((SELECT TOP 1 FIRST_LINK FROM dbo.DIS_FIRST WHERE LINK = @LINK_ARCH),@LINK_ARCH)

SET @DATE_BEGIN_P = ISNULL((SELECT TOP 1 DATE1 FROM dbo.DIS WHERE LINK = @varKSRefDoc),@DATE_BEGIN)

SET @RP = 2
---Определение расчетного периода
DECLARE @NUMBER VARCHAR(10), @DATE_DOC DATETIME

SELECT 
	@DATE_BEGIN_RP = dbo.DateBeginOfYear(DATE_BEGIN), 
	@DATE_DOC = D.[DATE],
	@LINK_DEP = D.LINK_DEP,
	@NUMBER = D.NUMBER
FROM
	DBO.SDOC D 
	INNER JOIN dbo.sdoc_adis SD ON SD.LINK_UP = D.LINK
WHERE 
	D.LINK = @LINK_DOC

IF ISNULL(@LINK_DOC,0)  = 0
BEGIN
	exec dbo.SALARY_NEXT_NUM @NUMBER OUT, 'DOCUMENTS_ADD_ARCHE'
	SET @DATE_DOC = (Select top 1 WORKDATE from dbo.USER_DATES)
END	

IF @DATE_BEGIN_RP IS NULL OR YEAR(@DATE_BEGIN_RP) >= YEAR(@DATE_BEGIN_P) - @RP
	SET @DATE_BEGIN_RP = dbo.ConvertDMY2Date(1,1,YEAR(@DATE_BEGIN_P)- @RP)

SET @DATE_END_RP = dbo.ConvertDMY2Date(31,12,YEAR(@DATE_BEGIN_RP) + (@RP-1))

---Учитываем заданные года для расчетного периода
DECLARE @YEAR1 INT, @YEAR2 INT, @YEAR_M INT
SELECT TOP 1 @YEAR1 = YEAR1, @YEAR2 = YEAR2 FROM dbo.DIS D INNER JOIN dbo.VAC_PERIOD_CHANGE C ON C.LINK_EMPL = D.REF_EMPL
WHERE D.LINK = @LINK_ARCH AND D.DATE1 BETWEEN C.DATE1 AND C.DATE2

IF ISNULL(@YEAR1,0) > 0 OR ISNULL(@YEAR2,0) > 0
BEGIN

	SET @YEAR_M = (CASE WHEN ISNULL(@YEAR1,0) > ISNULL(@YEAR2,0) THEN ISNULL(@YEAR1,0) ELSE ISNULL(@YEAR2,0) END)
	SET @YEAR1 = (CASE WHEN ISNULL(@YEAR1,0) <= ISNULL(@YEAR2,0) THEN ISNULL(@YEAR1,0) ELSE ISNULL(@YEAR2,0) END)
	SET @YEAR2 = @YEAR_M

	SET @DATE_BEGIN_RP = dbo.ConvertDMY2Date(1,1,@YEAR1)
	SET @DATE_END_RP = dbo.ConvertDMY2Date(31,12,@YEAR2)

END	
ELSE
BEGIN
	SET @YEAR1 = YEAR(@DATE_BEGIN_RP)
	SET @YEAR2 = YEAR(@DATE_END_RP)
END	
-----------------------------------------------------------------

SELECT TOP 1 @LINK_PERS = PERS_LINK,  @SystPay = SYST_PAY, @DEP_LINK = ISNULL(@DEP_LINK,DEP_LINK)
FROM dbo.EMPL WHERE LINK = @LINK_EMPL

--Количество ставок на начало больничного
DECLARE @EmplNumStake NUMERIC(5,2), @DEFAULT_KBK INT
SELECT @EmplNumStake = num_stake, @DEFAULT_KBK = LINK_KBK FROM dbo.SA_EMPLS_INFO(@DATE_BEGIN_P,@LINK_EMPL)
SET @DEFAULT_KBK = ISNULL((SELECT CH.NEW_LINK FROM dbo.SAL_SFIN_CHANGES(@DATE_BEGIN) CH WHERE CH.LINK = @DEFAULT_KBK),@DEFAULT_KBK)

 --если страховой стаж работника менее 6 месяцев, то предел ус-танавливается в размере 1 МРОТ
IF @STAGE_Y < 1 AND @STAGE_M < 6 
	SET @LIMIT = 2

--- Сохранить параметры расчёта
SELECT @varKSsoLink = LINK FROM dbo.s_objects  WHERE CODE = 'DOCUMENTS_ADD_ARCHE'

EXECUTE dbo.SALARY_UPD_SDOC @LINK_DOC OUTPUT, @varKSsoLink, @NUMBER,@DATE_DOC,@comment,0,null,0, @LINK_DEP

IF not exists(select link_up from dbo.sdoc_adis  where link_up =@LINK_DOC)
		INSERT INTO dbo.sdoc_adis WITH (ROWLOCK) (LINK_UP,LINK_EMPL,LINK_PAY,DATE_BEGIN,SR_ZAR,SR_PREM,TYP_PERIOD,LIMIT,REF_DOC)
		VALUES (@LINK_DOC, @LINK_EMPL,@LINK_PAYS,@DATE_BEGIN_RP,0,0,@TYP_PERIOD,@LIMIT,@LINK_ARCH)
ELSE
		UPDATE dbo.sdoc_adis WITH (ROWLOCK) 
		SET 	LINK_EMPL=@LINK_EMPL, LINK_PAY=@LINK_PAYS, DATE_BEGIN=@DATE_BEGIN_RP, 
				SR_PREM=0, TYP_PERIOD=@TYP_PERIOD, LIMIT=@LIMIT, REF_DOC=@LINK_ARCH
		WHERE LINK_UP=@LINK_DOC

---------------------------------------------------------------------------------------
--Ограничивать количество оплачиваемых дней в каленарном году
DECLARE @ARCHE_OPT9 TINYINT
SET @ARCHE_OPT9 = dbo.sa_get_option_by_code('ARCHE_OPT9')

-- Больной член семьи по этому больничному
DECLARE @LINK_DIS_PERSON INT 

--Ограничения по количеству оплачиваемых дней по данному больничному
IF @ARCHE_OPT9 = 1 BEGIN

	SELECT @LINK_DIS_PERSON = ISNULL(REF_PERS_KID, @LINK_PERS) FROM dbo.SDOC_DIS WHERE LINK_UP = @LINK_ARCH

	DECLARE @MAX_DAYS INT, @MAX_DAYS_IVENT INT, @SUM_DAYS INT
	SELECT 
		  @MAX_DAYS = N.MAX_DAYS, 
		  @MAX_DAYS_IVENT = N.MAX_DAYS_IVENT,
		  @SUM_DAYS = ISNULL(
			( --Вычисляем количество дней больничных, за которые начислили больничные
			SELECT SUM(DAYS)
			FROM
			(	SELECT T.DATE1, [DAYS] = MAX(T.[DAYS])
				FROM
					dbo.SDOC D
					INNER JOIN dbo.SDOC_ADIS A ON D.LINK = A.LINK_UP
					INNER JOIN dbo.SDOC_ADIS_TABLE1 T ON T.LINK_UP = D.LINK
					INNER JOIN dbo.SDOC_DIS SD ON A.REF_DOC = SD.LINK_UP AND A.LINK_EMPL = SD.LINK_EMPL
				WHERE
					SD.[TYPE] = N.LINK
					AND YEAR(@DATE_DOC) BETWEEN YEAR(T.DATE1) AND YEAR(T.DATE2)
					AND SD.LINK_EMPL = @LINK_EMPL
					AND ISNULL(SD.REF_PERS_KID, @LINK_PERS) = @LINK_DIS_PERSON
					AND SD.LINK_UP <> @LINK_ARCH --Данный больничный не учитываем
					AND SD.DATE1 <= @DATE_BEGIN --Проверяем только по предыдущим больничным
				GROUP BY T.DATE1
				) D
			)
			,0)
	FROM 
			dbo.NETRUD N
	WHERE
		  N.LINK = @REF_TYP_ARHE
		  AND @ARCHE_OPT9 = 1
END	

SELECT @MAX_DAYS = ISNULL(@MAX_DAYS,9999), @MAX_DAYS_IVENT = ISNULL(@MAX_DAYS_IVENT,9999), @SUM_DAYS = ISNULL(@SUM_DAYS,0)

--Столько осталось оплатить
SET @MAX_DAYS = (CASE WHEN @MAX_DAYS > @SUM_DAYS THEN @MAX_DAYS - @SUM_DAYS ELSE 0 END)
--Можно оплатить столько дней
SET @MAX_DAYS_IVENT = (CASE WHEN @MAX_DAYS_IVENT < @MAX_DAYS THEN @MAX_DAYS_IVENT ELSE @MAX_DAYS END)
-----------------------------------------------------------------------------------

---Определение процента оплаты по стажу
DECLARE @RercStag NUMERIC(18,2)

SELECT TOP 1 
	@RercStag = P 
FROM 
	dbo.DOCUMENTS_ADD_ARCH_SPR1 SPR1 
WHERE 
	@DATE_BEGIN BETWEEN SPR1.DATE_BEGIN AND SPR1.DATE_END
	AND @STAGE_Y BETWEEN SPR1.STAGE1 AND SPR1.STAGE2

DECLARE
	@PERCENT numeric(18,2), --Процент оплаты
	@Opt  tinyint, -- 1 - учитывать настройки справочника, 0 - нет
	@Stag  tinyint, -- 1 за первые N дней учитывать проценты по стажу, 0 - использовать указанй процент Perc1
	@Stag2  tinyint, -- 1 за последующие дни учитывать проценты по стажу, 0 - использовать указанй процент Perc2
	@Day1g  INT, --- количество первых дней, которые оплачивается Perc1
	@Perc1  numeric(18,2),
	@Perc2  numeric(18,2),
	@Day2_Payer  tinyint -- 0 - Первые два дня больничного оплачивает ФСС, 1 - Первые два дня больничного оплачивает Работодатель

SELECT @Stag = ISNULL(stag,0), @Stag2 = ISNULL(stag2,0), @Day2_Payer = (CASE WHEN ISNULL(@extension_DIS,0) = 0 THEN ISNULL(day2_payer,0) ELSE 0 END), 
	@Opt = ISNULL(opt,0), @Perc1 = ISNULL(perc1,0), @Perc2 = ISNULL(perc2,0),
	@Day1g = (CASE WHEN ISNULL(day1,0) = 1 THEN 0 ELSE ISNULL(day1,0) END) 
FROM DBO.KD_NETRUD where link = @REF_TYP_ARHE

IF @RECALC = 0  --- Расчет сумм по видам начислений
BEGIN
	--- Промежуточная база расчета
	CREATE TABLE #BASE1 (
		PERIOD DATETIME,
		CODE_PAY VARCHAR(254),
		NAME_PAY VARCHAR(254), 
		WAY_CALC INT,
		LINK_PAY INT,
		SUMMA NUMERIC(18,2),
		KOEF  NUMERIC(18,2),
		LINK_INC INT,
		LINK_VKR INT,
		DATE1 DATETIME,
		DATE2 DATETIME
	)

	DECLARE @Cur1 CURSOR, @CUR_EPML INT
	DECLARE @Cur2 CURSOR, @M INT, @Y INT, @PER DATETIME

	DECLARE @ARCHE_OPT4 TINYINT
	SET @ARCHE_OPT4 = dbo.sa_get_option_by_code('ARCHE_OPT4')

	SET @Cur1 = CURSOR FORWARD_ONLY
	FOR SELECT DISTINCT LINK FROM dbo.EMPL E-- INNER JOIN dbo.EMPL_STATUS(@DATE_BEGIN) S on E.link = S.empl_link --AND STATUS <= 2
		WHERE DEP_LINK = @LINK_DEP AND (@ARCHE_OPT4 = 1 AND PERS_LINK = @LINK_PERS) OR (@ARCHE_OPT4 = 0 AND E.link = @LINK_EMPL)

	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @CUR_EPML
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			
			SET @Cur2 = CURSOR FORWARD_ONLY
			FOR 
				SELECT m, y, DATE_BEGIN FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) WHERE Y = @YEAR1 OR Y = @YEAR2
			OPEN @Cur2
			FETCH NEXT FROM @Cur2 INTO @M, @Y, @PER
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN
			
				INSERT INTO #BASE1 (CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, KOEF, LINK_INC, LINK_VKR, DATE1, DATE2)
				exec dbo.SALARY_BASE_SUM_PAY_MONTH_DIF_PERIODS @LINK_PAYS, @CUR_EPML, @M, @Y			
				
				UPDATE #BASE1 SET PERIOD = @PER WHERE PERIOD IS NULL
				UPDATE #BASE1 SET LINK_VKR = @DEFAULT_KBK WHERE LINK_VKR IS NULL
			
				END
				FETCH NEXT FROM @Cur2 INTO @M, @Y, @PER
			END
		
			CLOSE @Cur2
			DEALLOCATE @Cur2

		END
		FETCH NEXT FROM @Cur1 INTO @CUR_EPML
	END
	
	CLOSE @Cur1 
	DEALLOCATE @Cur1

	INSERT INTO #BASE1 (PERIOD, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, KOEF, LINK_INC, LINK_VKR, DATE1, DATE2)
	SELECT dbo.ConvertDMY2Date(01,12,YEAR_SAL), '---', 'Заработок у других работодателей', 1, 0, SUMMA, 1, 0, @DEFAULT_KBK, dbo.ConvertDMY2Date(01,12,YEAR_SAL), dbo.ConvertDMY2Date(31,12,YEAR_SAL)  
	FROM [dbo].[SAL_OTHER_DEP] 
	WHERE ACTIVE = 1 AND YEAR_SAL IN (@YEAR1,@YEAR2) AND LINK_EMPL = @LINK_EMPL 

	--- Определим, делать ли расчет в разрезе КБК
	DECLARE @ARCHE_OPT5 TINYINT
	SET @ARCHE_OPT5 = dbo.sa_get_option_by_code('ARCHE_OPT5')

	/*Заменяем источники финансирования в базовых начислениях с учетом истории изменений источников*/
	UPDATE B SET B.LINK_VKR = CH.NEW_LINK
	FROM #BASE1 B INNER JOIN dbo.SAL_SFIN_CHANGES(@DATE_BEGIN) CH ON CH.LINK = B.LINK_VKR

	--
	Select 
		PERIOD = dbo.ConvertDMY2Date(31,12,YEAR(MIN(PERIOD))), PERIOD1 = YEAR(PERIOD), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, 
		SUMMA = SUM( CASE WHEN WAY_CALC = 6 AND (DATEDIFF(MONTH,DATE1, DATE2) + 1) <> 0 AND @UCHET_PREM = 1 THEN 
					CONVERT(NUMERIC(18,2), SUMMA * 
						(
							(DATEDIFF(MONTH,CASE WHEN DATE1 <= dbo.ConvertDMY2Date(1,1,@YEAR1) THEN dbo.ConvertDMY2Date(1,1,@YEAR1) ELSE DATE1 END,
								CASE WHEN DATE2 >= dbo.ConvertDMY2Date(31,12,@YEAR1) THEN dbo.ConvertDMY2Date(31,12,@YEAR1) ELSE DATE2 END) + 1)
						+	CASE WHEN @YEAR1 <> @YEAR2 THEN
								(DATEDIFF(MONTH,CASE WHEN DATE1 <= dbo.ConvertDMY2Date(1,1,@YEAR2) THEN dbo.ConvertDMY2Date(1,1,@YEAR2) ELSE DATE1 END,
									CASE WHEN DATE2 >= dbo.ConvertDMY2Date(31,12,@YEAR2) THEN dbo.ConvertDMY2Date(31,12,@YEAR2) ELSE DATE2 END) + 1)								
							ELSE 0 END
						)		
						/ (DATEDIFF(MONTH,DATE1, DATE2) + 1))
				ELSE SUMMA END),
		KOEF, LINK_INC, LINK_VKR = (CASE WHEN @ARCHE_OPT5 = 1 then LINK_VKR else @DEFAULT_KBK end)
	INTO #BASE
	from #BASE1 
	group by YEAR(PERIOD), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, KOEF, LINK_INC, (CASE WHEN @ARCHE_OPT5 = 1 then LINK_VKR else @DEFAULT_KBK end)

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

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

	DELETE FROM dbo.SDOC_ADIS_TABLE3  WHERE LINK_UP = @LINK_DOC

	DECLARE @SCRIPT VARCHAR(8000)
	
	SET @SCRIPT = ' INSERT INTO dbo.SDOC_ADIS_TABLE3 (LINK_UP, ORDERS, LINK_PAY, LINK_KBK, SUMMA1, SUMMA2)'  
			+ ' Select ' + CONVERT(VARCHAR(20),@LINK_DOC) + ', 0, LINK_PAY, LINK_VKR'  
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = @YEAR1 )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) <= @YEAR1 ))
				+ ',0)' ELSE ',0' END
			+ CASE WHEN @YEAR1 <> @YEAR2 AND EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = @YEAR2 )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) <= @YEAR2 ))
				+ ',0)' ELSE ',0' END
		+ ' from ' + @PAYS_MONTS
	
	EXEC  (@SCRIPT)

	SET @I = 0
	UPDATE dbo.SDOC_ADIS_TABLE3  
	SET @I = @I+1, ORDERS = @I
	WHERE LINK_UP = @LINK_DOC
	
END -- IF @RECALC = 0

-- Время
DECLARE @WTIME TABLE(Y INT)
INSERT INTO @WTIME (Y)
SELECT DISTINCT Y FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) WHERE Y = @YEAR1 OR Y = @YEAR2

IF @RECALC < = 1 --- Расчет сумм по месяцам
BEGIN
	-- Расчет отработанного времени для каждого отрезочка времени
		---
	DECLARE @TABLE2 TABLE (Y INT, M INT, LINK_KBK INT, SUMMA_ZP NUMERIC(18,2), SUMMA_PR NUMERIC(18,2), DAYS INT, HOURS NUMERIC(18,2), DAYS_NORM INT, HOURS_NORM NUMERIC(18,2))
	INSERT INTO @TABLE2
	SELECT  
		Y = T.Y,
		M = 12,
		ISNULL(B.LINK_KBK,@DEFAULT_KBK),
		SUMMA_ZP = SUM(SUMMA),
		SUMMA_PR = 0,
		0,0,0,0
	FROM 
		@WTIME T LEFT JOIN
		(
		Select PERIOD = dbo.DateEndOfYear(@DATE_BEGIN_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfYear(@DATE_BEGIN_RP), 
			DATE2 = dbo.DateEndOfYear(@DATE_BEGIN_RP),	
			SUMMA = T3.SUMMA1 
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA1,0) <> 0
	UNION ALL 
		Select PERIOD = dbo.DateEndOfYear(@DATE_END_RP), LINK_PAY, LINK_KBK, 
			DATE1 = dbo.DateBeginOfYear(@DATE_END_RP), 
			DATE2 = dbo.DateEndOfYear(@DATE_END_RP),	
			SUMMA = T3.SUMMA2  
		FROM dbo.SDOC_ADIS_TABLE3 T3  WHERE LINK_UP = @LINK_DOC AND ISNULL(T3.SUMMA2,0) <> 0
	) AS B ON T.Y = YEAR(B.PERIOD)
	GROUP BY
		T.Y, B.LINK_KBK

	----
	DECLARE @LINK_PAY_FSS INT	
	SET @LINK_PAY_FSS = (SELECT TOP 1 LINK FROM dbo.PAYS WHERE [OBJECT] = 3 AND WAY_CALC = 2)

	----
	UPDATE @TABLE2
	SET SUMMA_PR = 
		(
			SELECT MAX(PREDEL) FROM dbo.DICTIONARY_RANGE D
			WHERE LINK_PAYS = @LINK_PAY_FSS 
					AND TARIF = 1 
					AND [PERCENT] > 0 
					AND [DATE] = (SELECT TOP 1 [DATE] 
										FROM dbo.DICTIONARY_RANGE D1 
										WHERE D1.TARIF = D.TARIF 
												AND D1.LINK_PAYS = D.LINK_PAYS 
												AND [DATE] <= dbo.ConvertDMY2Date(1,1,(CASE WHEN Y < 2010 THEN 2010 ELSE Y END))
									ORDER BY [DATE] DESC) 
		 )


	DECLARE @CurPR CURSOR, @y1 INT, @m1 INT, @y2 INT, @m2 INT, @link_kbk1 INT, @SUM_KBK NUMERIC(18,2)
	
	SET @CurPR = CURSOR FORWARD_ONLY

	FOR select y, m, link_kbk from @TABLE2 order by y, m
	
	OPEN @CurPR
	FETCH NEXT FROM @CurPR INTO @y1, @m1, @link_kbk1
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN

			IF ISNULL(@y2,0) <> ISNULL(@y1,0) OR ISNULL(@m2,0) <> ISNULL(@m1,0)
				SELECT @SUM_KBK = 0, @y2 = @y1, @m2 = @m1

			UPDATE @TABLE2 SET HOURS_NORM = CASE WHEN ISNULL(SUMMA_ZP,0) > ISNULL(SUMMA_PR-@SUM_KBK,0) 
												THEN CASE WHEN ISNULL(SUMMA_PR-@SUM_KBK,0) > 0 THEN ISNULL(SUMMA_PR-@SUM_KBK,0) ELSE 0 END
												ELSE ISNULL(SUMMA_ZP,0) END
			WHERE @y1 = Y AND @m1 = M AND isnull(@link_kbk1,0) = isnull(link_kbk,0)

			SET @SUM_KBK = @SUM_KBK + ISNULL( (SELECT SUMMA = SUMMA_ZP	FROM @TABLE2 WHERE @y1 = Y AND @m1 = M AND isnull(@link_kbk1,0) = isnull(link_kbk,0)),0)

		END
	
		FETCH NEXT FROM @CurPR INTO @y1, @m1, @link_kbk1
	END
	
	CLOSE @CurPR
	DEALLOCATE @CurPR

	UPDATE A
	SET SUMMA_ZP = 
		CASE WHEN (SELECT SUM(B.SUMMA_ZP) FROM @TABLE2 B WHERE A.Y = B.Y AND A.M = B.M) > 0 THEN
						A.SUMMA_ZP / (SELECT SUM(B.SUMMA_ZP) FROM @TABLE2 B WHERE A.Y = B.Y AND A.M = B.M)
						* (SELECT SUM(B.HOURS_NORM) FROM @TABLE2 B WHERE A.Y = B.Y AND A.M = B.M)
					ELSE 0 END	
	FROM @TABLE2 A

	UPDATE @TABLE2 SET SUMMA_PR = 0, HOURS_NORM = 0

	---
	DELETE FROM dbo.SDOC_ADIS_TABLE2  WHERE LINK_UP = @LINK_DOC
	
	INSERT INTO dbo.SDOC_ADIS_TABLE2 (LINK_UP, ORDERS, PERIOD, SUMMA, SUMMA_PREM, [DAYS], [HOURS], DAYS_N, HOURS_N, LINK_KBK)
	SELECT  @LINK_DOC, 0, dbo.ConvertDMY2Date(1, M, Y), SUMMA_ZP, SUMMA_PR, [DAYS],[HOURS],DAYS_NORM,HOURS_NORM, LINK_KBK
	FROM @TABLE2
	ORDER BY Y, M, LINK_KBK

	SET @I = 0
	UPDATE dbo.SDOC_ADIS_TABLE2  
	SET @I = @I+1, ORDERS = @I
	WHERE LINK_UP = @LINK_DOC
END	--IF @RECALC < = 1

DECLARE @RAION NUMERIC(18,2)
exec dbo.SA_EMPL_RAION_KOEF_BL @RAION OUT, @LINK_EMPL, @DATE_BEGIN

SET @RAION = CASE WHEN ISNULL(@RAION,0) <1 THEN 1 ELSE ISNULL(@RAION,0) END

DECLARE @SUM_LIMIT NUMERIC(18,4), @MINROT NUMERIC(18,2)
SET @MINROT = dbo.minrot2(@DATE_BEGIN) * (CASE WHEN @EmplNumStake <= 1 THEN @EmplNumStake ELSE 1 END) * 24

IF @RECALC < = 2 --- Расчет периодов больничного и определение средних сум
BEGIN		
	---Периоды больничного
	DECLARE
	 @DATE_RAB_END DATETIME,
	 @DATE_B DATETIME,
	 @R int	-- Первые 3 дня за счет работодателя
	
	---
	SELECT @R = @Day2_Payer * 3
	SELECT @DATE_RAB_END = DATEADD(DAY,@R-1,@DATE_BEGIN), @DATE_B = CASE WHEN @R > 0 THEN DATEADD(DAY,@R,@DATE_BEGIN) ELSE @DATE_BEGIN END

	/*Если это продолжение, то за счет работодателя ни чего не оплачивается, предполагается, что первый больничный был не менее 2-х дней*/
	
	---Разбивка периодов на периоды по настройкам оплаты больничного
	DECLARE
	 @DATE_BEGIN1 DATETIME,
	 @DATE_END1 DATETIME 

	--Обработка продолжения б/л
	DECLARE @LINK_BL_OLD INT, @DATE_BEG_OLD DATETIME, @DATE_END_OLD DATETIME
	SET @LINK_BL_OLD = (SELECT TOP 1 REF_DOC FROM dbo.DIS WHERE LINK = @LINK_ARCH)

	/*УЧИТЫВАЕМ, ЧТО ЭТО МОЖЕТ БЫТЬ ПРОДОЛЖЕНИЕМ БОЛЬНИЧНОГО ЛИСТА*/
	--Периоды продолжаемого б/л	
	SELECT @DATE_BEG_OLD = DATE1, @DATE_END_OLD = DATE2 FROM dbo.DIS WHERE LINK = @LINK_BL_OLD
	--расширить периоды за счет других продолжений
	IF EXISTS (SELECT LINK FROM dbo.DIS WHERE REF_DOC = @LINK_BL_OLD AND LINK <> @LINK_ARCH AND DATE1 < @DATE_BEGIN)
		SET @DATE_END_OLD = (SELECT MAX(DATE2) FROM dbo.DIS WHERE REF_DOC = @LINK_BL_OLD AND LINK <> @LINK_ARCH AND DATE1 < @DATE_BEGIN)

	IF @DATE_BEG_OLD IS NOT NULL
	BEGIN
		SET @Day1g = @Day1g - (DATEDIFF(DAY,@DATE_BEG_OLD,@DATE_END_OLD) + 1)
		SET @Day1g = CASE WHEN @Day1g < 0 THEN 0 ELSE @Day1g END
	END

	SET @DATE_END1 = (CASE WHEN DATEADD(DAY,@Day1g-1,@DATE_BEGIN) < @DATE_END THEN DATEADD(DAY,@Day1g-1,@DATE_BEGIN) ELSE @DATE_END END)
	SET @DATE_BEGIN1 = (CASE WHEN @DATE_END1 +1 < @DATE_END THEN @DATE_END1 +1 ELSE @DATE_END END)

	--== ФОРМИРНОВАНИЕ ПЕРИОДОВ ДЛЯ ОПЛАТЫ В РАЗРЕЗЕ ГОДА, МЕСЯЦА, ПЛАТЕЛЬЩИКА И ПРОЦЕНТОВ
	DECLARE @PERIODY TABLE ( ord int identity(1,1), DATE_BEGIN DATETIME, DATE_END DATETIME, R TINYINT, PERC NUMERIC(18,2), DH NUMERIC(18,2), DH_NORM NUMERIC(18,6), I TINYINT, SUM_LIMIT NUMERIC(20,4))
	
	--- 1. Разбивка на периоды по плательщикам и календарным месяцам
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, R, PERC, I)
	--- Определение плательщика
	select 
		DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_RAB_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_RAB_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 1, PERC = 0.00, 1 --Первое преобразование
	from dbo.months_ex(@DATE_BEGIN, @DATE_RAB_END)
	WHERE @R > 0
	UNION ALL
	select 
		DATE_BEGIN = (CASE WHEN @DATE_B > DATE_BEGIN THEN @DATE_B ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 0, PERC = 0.00, 1
	from dbo.months_ex(@DATE_B, @DATE_END)
	UNION
	--- Определение процента в зависимости от настроек больничного
	SELECT  
		DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_END1 < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END1 ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 0, PERC = CASE WHEN @Stag = 0 THEN @Perc1 ELSE @RercStag END, 1
	from dbo.months_ex(@DATE_BEGIN, @DATE_END1 )
	WHERE 	ISNULL(@OPT,0) = 1 
	UNION ALL
	SELECT  
		DATE_BEGIN = (CASE WHEN @DATE_BEGIN1 > DATE_BEGIN THEN @DATE_BEGIN1 ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 0, PERC = CASE WHEN @Stag2 = 0 THEN @Perc2 ELSE @RercStag END, 1
	from dbo.months_ex(@DATE_BEGIN1, @DATE_END )
	WHERE 	ISNULL(@OPT,0) = 1
	ORDER BY DATE_BEGIN, DATE_END

	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, R, PERC, I)
	--- Установка процента, если настройки не заданы
	SELECT  
		DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
		DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
		P = 0, PERC = @RercStag, 1
	from dbo.months_ex(@DATE_BEGIN, @DATE_END )
	WHERE 	ISNULL(@OPT,0) = 0 
	ORDER BY DATE_BEGIN, DATE_END

	--- 2. Все границы периодов
	DECLARE @PERIODY1 TABLE (ORD INT IDENTITY(1,1), PER DATETIME)
	INSERT INTO @PERIODY1 (PER)
	SELECT PER FROM (SELECT PER = DATE_BEGIN FROM @PERIODY UNION SELECT PER = DATE_END FROM @PERIODY) as P
	UNION ALL 
	SELECT PER FROM (SELECT PER = DATE_BEGIN FROM @PERIODY UNION SELECT PER = DATE_END FROM @PERIODY) as P
	WHERE PER = dbo.DateEndOfMonth(PER)
	ORDER BY PER	

	--- 3.Получение отрезков времени со сдвинутыми датами начала
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, I)
	SELECT 
		(CASE WHEN P1.PER = @DATE_BEGIN OR P1.PER = @DATE_END THEN P1.PER ELSE P1.PER + 1 END),
		ISNULL(P2.PER,P1.PER),
		2  --второе преобразование
	FROM 
		@PERIODY1 P1 LEFT JOIN @PERIODY1 P2 ON P1.ORD = P2.ORD - 1

	---Корректировка
	UPDATE @PERIODY
	SET DATE_BEGIN  = DATE_BEGIN + 1
	WHERE I = 2 AND DATE_BEGIN <> DATE_END AND DATE_BEGIN = dbo.DateEndOfMonth(DATE_BEGIN)

	--- 4. Исключение перекрывающихся периодов
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, I)
	SELECT AP.DATE_BEGIN, AP.DATE_END, 3 FROM @PERIODY AP
	WHERE AP.I = 2 AND NOT EXISTS (SELECT * FROM @PERIODY AP1 WHERE AP1.I = 2 AND AP.DATE_BEGIN > AP1.DATE_BEGIN AND AP.DATE_END <= AP1.DATE_END)

	-- Особый случай, когда боьничный один день
	IF @DATE_BEGIN = @DATE_END 
		UPDATE @PERIODY SET DATE_BEGIN = @DATE_BEGIN, DATE_END = @DATE_END
		WHERE DATE_END >= @DATE_BEGIN

	--- 5. Расстановка плательщика и процентов по периодам
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, I, R, PERC)
	Select 
		P3.DATE_BEGIN, P3.DATE_END, 4,
		R =  ISNULL((SELECT TOP 1 P1.R FROM @PERIODY P1 WHERE I = 1 AND P1.R = 1 AND (P3.DATE_BEGIN BETWEEN P1.DATE_BEGIN AND P1.DATE_END) AND (P3.DATE_END BETWEEN P1.DATE_BEGIN AND P1.DATE_END)  order by ord),0),
		PERC = ISNULL((SELECT TOP 1 P1.PERC FROM @PERIODY P1 WHERE I = 1 AND P1.PERC > 0 AND (P3.DATE_BEGIN BETWEEN P1.DATE_BEGIN AND P1.DATE_END) AND (P3.DATE_END BETWEEN P1.DATE_BEGIN AND P1.DATE_END) order by ord),0)
	FROM @PERIODY P3 
	WHERE P3.I = 3 
	
	--- 6. Соединение периодов
	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, I, R, PERC)
	Select 
		MIN(DATE_BEGIN), MAX(DATE_END), 5, R, PERC
	FROM @PERIODY P4 
	WHERE P4.I = 4 
	GROUP BY YEAR(DATE_BEGIN), MONTH(DATE_BEGIN), R, PERC
	
	DECLARE @ARCHE_OPT13 INT --Не начисять суммы за счёт ФСС 
	SET @ARCHE_OPT13 = dbo.SA_GET_OPTION_BY_CODE('ARCHE_OPT13')
	IF @ARCHE_OPT13 = 1
		DELETE FROM @PERIODY WHERE I = 5 AND R = 0
	
	--== ПОЛУЧЕНИЕ ПЕРИОДОВ ЗАВЕРШЕНО!
	
	---Определение предела

	-- увеличенный на размер районного коэффициента
	--Сумма МРОТ должна быть в пределах количества ставок, т.к. по ней идет расчет за полностью отработанное время на полной ставке

	DECLARE @LINK_FSS INT, @MAX_SUM_FSS NUMERIC(18,2)
	SET @LINK_FSS = (SELECT TOP 1 LINK FROM dbo.PAYS WHERE [OBJECT] = 3 AND WAY_CALC = 2)
	
	DECLARE @T_MAX_SUM_FSS TABLE (SUMMA NUMERIC(18,2))

	----
	INSERT INTO @T_MAX_SUM_FSS (SUMMA)
	SELECT MAX_SUM_FSS = 
				(
					SELECT MAX(PREDEL) FROM dbo.DICTIONARY_RANGE D
					WHERE LINK_PAYS = @LINK_FSS 
							AND TARIF = 1 
							AND [PERCENT] > 0 
							AND [DATE] = (SELECT TOP 1 [DATE] 
												FROM dbo.DICTIONARY_RANGE D1 
												WHERE D1.TARIF = D.TARIF 
														AND D1.LINK_PAYS = D.LINK_PAYS 
														AND [DATE] <= dbo.ConvertDMY2Date(1,1,(CASE WHEN Y < 2010 THEN 2010 ELSE Y END))
											ORDER BY [DATE] DESC) 
				 )
	FROM 
		@WTIME T
		
	SET @MAX_SUM_FSS = (SELECT SUM(SUMMA) FROM @T_MAX_SUM_FSS)
		--(SELECT SUM(SUMMA)/(12*COUNT(*)) FROM @T_MAX_SUM_FSS)
	IF ISNULL(@MAX_SUM_FSS,0) = 0
		SET @MAX_SUM_FSS = dbo.sa_get_option_by_code('ARCHE_OPT1')

	DECLARE @D NUMERIC(18,6)
--	IF EXISTS( SELECT * FROM [dbo].[NETRUD] N INNER JOIN [dbo].[SDOC_DIS] SD ON [SD].[TYPE] = [N].[LINK] WHERE [N].[DEKRET] = 1 AND SD.LINK_UP = @LINK_ARCH)
--		SET @D = dbo.sa_get_option_by_code('VAC_CHILD_OPT5') * 24
--	ELSE
	SET @D = 730 --730.000000/24

	----
	UPDATE @PERIODY
	SET 

		DH = DATEDIFF(DAY,DATE_BEGIN, DATE_END)+1,
	
		DH_NORM = 
				CASE WHEN DATE_BEGIN <= '20091231' THEN 
					DAY(dbo.DateEndOfMonth(DATE_BEGIN))
				ELSE
					@D
				END,			
		SUM_LIMIT = 
				CONVERT(NUMERIC(18,2),
					CASE @LIMIT
					WHEN 2 THEN @MINROT * @RAION -- в размере 1 МРОТ
					WHEN 3 THEN 
						CASE WHEN DATE_BEGIN <= '20091231' THEN 	
							(CASE WHEN @dekret = 0 THEN dbo.sa_get_option_by_code('ARCHE_OPT7') ELSE dbo.sa_get_option_by_code('ARCHE_OPT8') END) * @RAION 
						ELSE	
							-- !!! С 1 января 2010 года максимальный размер пособия одинаковый по все территории РФ!!!: Максимум без учета районныйх, но с учетом стажа
							@MAX_SUM_FSS
						END
					ELSE 0
					END 
				)				
	WHERE I = 5

	---------------------------------------------------------------------------------------
	--Откорректируем оплачиваемые дни за каждый период
	DECLARE @Cur3 CURSOR
	Declare @NEXT_DATE DATETIME

	IF @ARCHE_OPT9 = 1
	BEGIN
		SET @Cur3 = CURSOR FORWARD_ONLY

		FOR SELECT DATE_BEGIN FROM @PERIODY WHERE I = 5 AND YEAR(@DATE_DOC) BETWEEN YEAR(DATE_BEGIN) AND YEAR(DATE_END) ORDER BY DATE_BEGIN
		
		OPEN @Cur3
		FETCH NEXT FROM @Cur3 INTO @NEXT_DATE
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN

				UPDATE @PERIODY
				SET DH = (CASE WHEN DH < @MAX_DAYS_IVENT THEN DH ELSE @MAX_DAYS_IVENT END)
				WHERE I = 5 AND DATE_BEGIN = @NEXT_DATE
				
				SELECT @MAX_DAYS_IVENT = (CASE WHEN DH < @MAX_DAYS_IVENT THEN @MAX_DAYS_IVENT - DH ELSE 0 END)
				FROM @PERIODY
				WHERE I = 5 AND DATE_BEGIN = @NEXT_DATE

			END
		
			FETCH NEXT FROM @Cur3 INTO @NEXT_DATE
		END
		
		CLOSE @Cur3
		DEALLOCATE @Cur3
	END	
	---------------------------------------------------------------------------------------

	---
	DECLARE @REP_SUMMA_PR NUMERIC(18,2), @SUMMA_ZP NUMERIC(18,2), @SUMMA_PR NUMERIC(18,2), @NORM NUMERIC(18,2), @WORK NUMERIC(18,2), @SR_ZP NUMERIC(20,4)
	
	SELECT 
		@SUMMA_ZP = ISNULL(SUM(SUMMA),0),
		@SUMMA_PR = 0
	FROM dbo.SDOC_ADIS_TABLE2 WHERE LINK_UP = @LINK_DOC

	----	
	DECLARE @KBK_KOEF TABLE (LINK_KBK INT, KOEF NUMERIC(18,4))
	DECLARE @SR_ZP_R numeric(20,4)

	---	
	SET @SR_ZP = CONVERT(NUMERIC(18,2),ISNULL(@SUMMA_ZP,0) / 730)
	SET @SR_ZP_R = @SR_ZP
	
	IF ISNULL(@SR_ZP,0) = 0  BEGIN
		DELETE FROM @KBK_KOEF
		INSERT INTO @KBK_KOEF (LINK_KBK, KOEF) 
		SELECT @DEFAULT_KBK, 1
	END 
	ELSE BEGIN
		---
		DECLARE @S NUMERIC(18,2)
		SET @S = ISNULL((SELECT SUM(SUMMA) FROM dbo.SDOC_ADIS_TABLE2 WHERE LINK_UP = @LINK_DOC),0)

		INSERT INTO @KBK_KOEF (LINK_KBK, KOEF) 
		SELECT LINK_KBK, CASE WHEN @S <> 0 THEN SUM(SUMMA) / @S ELSE 0 END 
		FROM dbo.SDOC_ADIS_TABLE2  WHERE LINK_UP = @LINK_DOC 
		GROUP BY LINK_KBK
	END
	---
	DELETE FROM dbo.SDOC_ADIS_TABLE1  WHERE LINK_UP = @LINK_DOC
	INSERT INTO dbo.SDOC_ADIS_TABLE1 (LINK_UP, ORDERS, DATE1, DATE2, SUM_LIMIT, [DAYS], [HOURS], SR_ZP, SUMMA, PERC, PAYER, LINK_KBK, KOEF_KBK)
	SELECT @LINK_DOC, 0, DATE_BEGIN, DATE_END, 
		LIMIT = CONVERT(NUMERIC(20,2), P.SUM_LIMIT / DH_NORM),
		DH,--(CASE WHEN @SystPay = 1 THEN DH ELSE 0 END),
		0,--(CASE WHEN @SystPay = 1 THEN 0 ELSE DH END),
		SR_ZP = NULL,
		0,
		PERC,
		R,
		K.LINK_KBK,
		K.KOEF
	FROM @PERIODY P INNER JOIN @KBK_KOEF K ON 1=1
	WHERE I = 5
	ORDER BY DATE_BEGIN

	UPDATE sdoc_adis WITH (ROWLOCK) 
	SET 	LINK_EMPL = @LINK_EMPL, LINK_PAY=@LINK_PAYS, DATE_BEGIN=@DATE_BEGIN_RP, SR_ZAR=@SR_ZP_R, SR_PREM=@SUMMA_PR, TYP_PERIOD=@TYP_PERIOD, LIMIT=@LIMIT, REF_DOC=@LINK_ARCH, INSTRUCT = 2
	WHERE LINK_UP = @LINK_DOC
	
END --@RECALC <= 2 

DECLARE @ARCHE_OPT10 TINYINT -- Мин. размер пособия при отсутсвии заработка выплачивать с учётом районного коэффицента
SET @ARCHE_OPT10 = dbo.SA_GET_OPTION_BY_CODE('ARCHE_OPT10')

DECLARE @SR_ZP_MINI numeric(20,4)
SET @SR_ZP_MINI = @MINROT * (CASE WHEN @ARCHE_OPT10 = 1 THEN @RAION ELSE 1 END)  / 730

SET @SR_ZP = ISNULL((SELECT TOP 1 SR_ZAR FROM dbo.sdoc_adis WHERE LINK_UP = @LINK_DOC),0)
SET @SR_ZP = CASE WHEN @SR_ZP < @SR_ZP_MINI THEN @SR_ZP_MINI ELSE @SR_ZP END

UPDATE dbo.SDOC_ADIS_TABLE1
SET 
	SR_ZP = convert(numeric(20,4),
			(CASE WHEN @SR_ZP < SUM_LIMIT OR @LIMIT = 4 AND @LIMIT <> 2 THEN @SR_ZP ELSE SUM_LIMIT END))
			* convert(numeric(20,4),(CASE WHEN PERC > 0 then PERC/100 else 0 end))
FROM 
	dbo.sdoc_adis A 
	INNER JOIN dbo.SDOC_ADIS_TABLE1 T ON A.LINK_UP = T.LINK_UP
WHERE 
	T.LINK_UP = @LINK_DOC AND KOEF_KBK IS NOT NULL
	
--Заменяю источник финансирования за счет ФСС
UPDATE dbo.SDOC_ADIS_TABLE1
SET 
	LINK_KBK = SF.[LINK_SS_SFIN]
FROM 
	dbo.sdoc_adis A 
	INNER JOIN dbo.SDOC_ADIS_TABLE1 T ON A.LINK_UP = T.LINK_UP
	INNER JOIN dbo.SAL_SFIN SF ON SF.LINK = T.LINK_KBK
WHERE 
	T.LINK_UP = @LINK_DOC AND PAYER = 0 AND SF.[LINK_SS_SFIN] IS NOT NULL
	

----
Select CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR, DAYS = SUM(CJ.DAYS), HOURS = SUM(CJ.HOURS), LINK_EKR, SUMMA = SUM(SUMMA)
INTO #SUM_OLD
from 
	dbo.SDOC_ADIS SA inner join dbo.CALCULATE_JURNAL CJ on CJ.LINK_DOC = SA.LINK_UP
	inner join dbo.sdoc d on CJ.LINK_DOC = d.link 
where
	ISNULL(@LINK_ARCH,0) > 0
	AND
	SA.REF_DOC = @LINK_ARCH
	and
	d.object = (Select top 1 link from s_objects where code = 'DOCUMENTS_ADD_ARCHE')
GROUP BY
	CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR, LINK_EKR

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

---- сопоставить старые
UPDATE dbo.SDOC_ADIS_TABLE1
SET 
	SUMMA_NEW = CONVERT(NUMERIC(18,2), T.SR_ZP * T.[DAYS] * KOEF_KBK),--(CASE WHEN @SystPay = 1 THEN T.[DAYS] ELSE T.[HOURS] END) * KOEF_KBK),
	SUMMA_OLD = ISNULL(SO.SUMMA,0),
	DAYS = COALESCE(T.DAYS,0) - COALESCE(SO.DAYS,0), 
	HOURS = COALESCE(T.HOURS,0) - COALESCE(SO.HOURS,0)
FROM 
	dbo.sdoc_adis A 
	INNER JOIN dbo.SDOC_ADIS_TABLE1 T ON A.LINK_UP = T.LINK_UP
	LEFT JOIN #SUM_OLD SO ON T.DATE1 = SO.DATE_BEGIN AND T.DATE2 = SO.DATE_END AND T.LINK_KBK = SO.LINK_VKR and PAYER = (CASE WHEN LINK_EKR=@LInkEKR213 then 0 else 1 end)
WHERE 
	T.LINK_UP = @LINK_DOC AND KOEF_KBK IS NOT NULL AND SR_ZP IS NOT NULL

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

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

--удалить пустые строки
DELETE FROM dbo.SDOC_ADIS_TABLE1
WHERE LINK_UP = @LINK_DOC AND ISNULL(SUMMA_NEW,0) = 0

SET @I = 0

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

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

---
SELECT @NUMBER = NUMBER,  @DATE_DOC = DATE from SDOC WHERE LINK = @LINK_DOC

if exists (select * from #SUM_OLD)
	set @comment = 'Перерасчет: ' + @comment

--- Сохрание расчета
EXECUTE dbo.SALARY_UPD_SDOC @LINK_DOC OUTPUT, @varKSsoLink, @NUMBER,@DATE_DOC,@comment,0,null,@SUMMA

IF @OPER = 1 
	exec dbo.SD_N_BOL_PROV @LINK_DOC

SET NOCOUNT OFF


GO


GRANT EXECUTE ON dbo.[SA_N_BOL_FILL2] TO PUBLIC

GO

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



CREATE PROCEDURE dbo.BB_UNLOAD_EXPORT_MODEL @varKSModelLink INT -- ВЫГРУЗКА МОДЕЛЕЙ
as
DECLARE 
	@varKSBlockLink INT,
	@varKSModelCode VARCHAR(5),
	@varKSModelVer  VARCHAR(10)
declare @tTemp table (TXT varchar(8000), ord int identity)

insert into @tTemp(TXT)
SELECT 'update EXPORT_MODELS set DATE_END   = ' + isnull('''' + replace(convert(varchar(10),MO1.DATE_END,102), '.', '') + '''', 'NULL') 
	+ ' where MODEL_VER = ''' + RTRIM(MO1.Model_Ver) + ''' AND CODE = ''' + RTRIM(MO1.Code) + ''''
FROM dbo.EXPORT_MODELS M1
inner join dbo.EXPORT_MODELS MO1 on MO1.CODE = M1.CODE and MO1.DATE_END is not null
WHERE M1.link_model = @varKSModelLink and MO1.MODEL_VER = (
	SELECT max(MO.MODEL_VER) 
	FROM dbo.EXPORT_MODELS M
	inner join dbo.EXPORT_MODELS MO on MO.CODE = M.CODE AND MO.link_model <> M.link_model
	WHERE M.link_model = @varKSModelLink)

insert into @tTemp(TXT)
SELECT 'DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = ''' + RTRIM(Model_Ver) + ''' AND CODE = ''' + RTRIM(Code) + '''
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 ''' + RTRIM(CODE) + ''',''' + RTRIM(NAME) + ''',''' + RTRIM(MODEL_VER) + ''',' + RTRIM(CONVERT(VARCHAR(10),ISONCE)) + ','''
		+ RTRIM(isnull(NORM_DOC,'')) + ''',''' + RTRIM(isnull(FILE_NAME_MASK,'')) + ''',''' + RTRIM(isnull(FILE_NAME_PROC,'')) + ''','''
		+ RTRIM(isnull(PROC_EXP,'')) + ''',''' + RTRIM(isnull(PROC_DOP_PARAM,'')) + ''',''' + RTRIM(isnull(DEP_NAME,'')) + ''',''' + RTRIM(isnull(PROG_SAVE,'')) + ''','
		+ isnull('''' + convert(varchar(10),DATE_END,104) + '''', 'NULL') + ' 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = ' + RTRIM(CONVERT(VARCHAR(10),ISONCE)) + ',
		NAME   = ''' + RTRIM(isnull(NAME,'')) + ''',
		NORM_DOC   = ''' + RTRIM(isnull(NORM_DOC,'')) + ''',
		FILE_NAME_MASK   = ''' + RTRIM(isnull(FILE_NAME_MASK,'')) + ''',
		FILE_NAME_PROC   = ''' + RTRIM(isnull(FILE_NAME_PROC,'')) + ''',
		PROC_EXP   = ''' + RTRIM(isnull(PROC_EXP,'')) + ''',
		PROC_DOP_PARAM   = ''' + RTRIM(isnull(PROC_DOP_PARAM,'')) + ''',
		PROG_SAVE   = ''' + RTRIM(isnull(PROG_SAVE,'')) + ''',
		DEP_NAME   = ''' + RTRIM(isnull(DEP_NAME,'')) + ''',
		DATE_END   = ' + isnull('''' + convert(varchar(10),DATE_END,104) + '''', 'NULL') + '
	where LINK_MODEL = @varKSModelLink'
FROM dbo.EXPORT_MODELS 
WHERE LINK_MODEL = @varKSModelLink

DECLARE BLOC_CUR CURSOR LOCAL STATIC READ_ONLY FOR
SELECT DISTINCT LINK_BLOCK 
FROM dbo.EXPORT_BLOCKS
WHERE LINK_MODEL = @varKSModelLink

OPEN BLOC_CUR
FETCH NEXT FROM BLOC_CUR INTO @varKSBlockLink

WHILE @@FETCH_STATUS = 0
BEGIN
	insert into @tTemp(TXT)
	SELECT 'set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = ''' + RTRIM(CODE) + '''
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,''' + RTRIM(CODE) + ''',' + RTRIM(ORDERS) + ',' + RTRIM(CONVERT(VARCHAR(10),ISONCE)) + ',''' + RTRIM(NAME) + ''',' + RTRIM(CONVERT(VARCHAR(10),OBLIGATORY)) + '
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = ' + RTRIM(ORDERS) + ',
			ISONCE = ' + RTRIM(CONVERT(VARCHAR(10),ISONCE)) + ',
			NAME   = ''' + RTRIM(NAME) + ''',
			OBLIGATORY = ' + RTRIM(CONVERT(VARCHAR(10),OBLIGATORY)) + '
	where LINK_BLOCK = @varKSBlockLink'
	FROM EXPORT_BLOCKS
	WHERE LINK_BLOCK = @varKSBlockLink
	--select @varKSBlockLink
	insert into @tTemp(TXT)
	SELECT 'if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = ''' + RTRIM(EF.CODE) + ''')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= ' + RTRIM(CONVERT(VARCHAR(10),EF.ORDERS)) + ',
		NAME   		= ''' + RTRIM(ISNULL(EF.NAME,'NULL')) + ''',
		VAL_TYPE 	= ''' + RTRIM(EF.VAL_TYPE) + ''',
		VAL_LEN 	= ' + RTRIM(ISNULL(CONVERT(VARCHAR(10),EF.VAL_LEN),'NULL')) + ',
		VAL_LEN_EQ	= ' + RTRIM(CONVERT(VARCHAR(10),EF.VAL_LEN_EQ)) + ',
		NEED_CHECK	= ' + RTRIM(CONVERT(VARCHAR(10),EF.NEED_CHECK)) + ',
		OBLIGATORY	= ' + RTRIM(CONVERT(VARCHAR(10),EF.OBLIGATORY)) + ',
		ALIAS_CODE	= ''' + RTRIM(ISNULL(EF.ALIAS_CODE,'NULL')) + ''',
		CHECK_PROC	= ''' + RTRIM(EF.CHECK_PROC) + ''',
		VAL_LIST	= ''' + RTRIM(EF.VAL_LIST) + '''
	where LINK_BLOCK = @varKSBlockLink and CODE = ''' + RTRIM(EF.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, ' + RTRIM(CONVERT(VARCHAR(10),EF.ORDERS)) + ',''' + RTRIM(EF.CODE) + ''',''' + RTRIM(ISNULL(EF.NAME,'NULL')) + ''',''' + RTRIM(EF.VAL_TYPE) + ''',' + RTRIM(ISNULL(CONVERT(VARCHAR(10),EF.VAL_LEN),'NULL')) + ',' + RTRIM(CONVERT(VARCHAR(10),EF.VAL_LEN_EQ)) + ',' + RTRIM(CONVERT(VARCHAR(10),EF.NEED_CHECK)) + ',' + RTRIM(CONVERT(VARCHAR(10),EF.OBLIGATORY)) + ',''' + RTRIM(ISNULL(EF.ALIAS_CODE,'NULL')) + ''',''' + RTRIM(EF.CHECK_PROC) + ''',''' + RTRIM(EF.VAL_LIST) + ''''
	FROM EXPORT_FIELDS EF
	WHERE EF.LINK_BLOCK = @varKSBlockLink
	order by ORDERS
	FETCH NEXT FROM BLOC_CUR INTO @varKSBlockLink
END
CLOSE BLOC_CUR
DEALLOCATE BLOC_CUR
insert into @tTemp (TXT)
select 'GO'

SELECT TXT as [TEXT] from @tTemp order by ord


 


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,
	@LINK_SS_SFIN INT = 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,LINK_SS_SFIN)
		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,@LINK_SS_SFIN)

	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, LINK_SS_SFIN = @LINK_SS_SFIN
	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.[RN_CALC_164]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RN_CALC_164]

GO

/*******************************************************************************
	Кейсистемс (Keysystems), 2006
*******************************************************************************/
CREATE       procedure dbo.RN_CALC_164
	@LSF int=null,  -- линк  отчета
    @cVariant varchar(250)='' --наменование варианта в БКС
AS
create table  #tmp_calc164 (kod_bp varchar(10),name_bp varchar(200),kbk varchar(30),type_kbk int,rosp numeric(18,4),isp numeric(18,4))

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


declare @cstr varchar(1000)
declare @nastr int

--сбросим настройку, для перезаписи отчетов.
select top 1 @nastr=NEW_REPORT from dbo.I_REPORT_OPTIONS_COMMON 
--UPDATE REPORT_OPTIONS SET val_int=0  WHERE code='NEW_REPORT' 

declare @cStrVal varchar(100),@nameServer varchar(100),@nameBase varchar(100),@cTable_name varchar(250),@LF int,@varKSLinkSF int,@varKSLinkF int,@link_org int,@link_budg int,@link_tree int,@licount int,@level int,@pType int ,@pnomber int,@bDate datetime
select @LF=link_form,@link_org=link_organization , @link_budg=link_type_svod,@pTYPE=Period_type, @PNomber=period_number,@bdate=begin_date from report_saved_forms where link_saved_form=@LSF

--формируем команду выполнения
set @cTable_name = 'svod_calc164_'+db_name()+right('000000' + convert(VARchar(6), convert(int, 1000000 * rand())), 6)

exec X_GET_OPTION 'REPORT_ORTIONS_SERVER_BKS',0,@cStrVal output 	
set @nameServer=RTRIM(ISNULL(@cStrVal,''))
IF  @nameServer<>''
    set @nameServer='['+@nameServer+'].'

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

set @cstr='if exists (select * from '+RTRIM(@nameServer) + '[' + RTRIM(@nameBase) + '].dbo.sysobjects where id = object_id(N''['+@cTable_name+']'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1)
    drop table ['+@cTable_name+']'
print @cstr
execute(@cstr)

 set @cstr=' execute '+RTRIM(@nameServer) + '[' + RTRIM(@nameBase) + '].dbo.m_exec_squery_var 0,'''','''+@cVariant+''',
    ''@dDate_1='''''+convert(varchar(20),dbo.DateBeginOfYear(@bdate),112)+''''',@dDate_2='''''+convert(varchar(20),(@bdate),112)+''''''''+','''+@cTable_name+''''
print @cstr
execute(@cstr)
set @cstr='
    INSERT #tmp_calc164 (kod_bp,name_bp,kbk,type_kbk,rosp,isp)
    select kod_bp,name_bp,kbk,type_kbk,rosp,isp from '+RTRIM(@nameServer) + '[' + RTRIM(@nameBase) + '].dbo.'+@cTable_name
print @cstr
execute(@cstr)

set @cstr='if exists (select * from '+RTRIM(@nameServer) + '[' + RTRIM(@nameBase) + '].dbo.sysobjects where id = object_id(N''['+@cTable_name+']'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1)
    drop table ['+@cTable_name+']'
execute(@cstr)

--данные в табличке
--найдем какие организации нам нужны
--по lsf найдем link_org и link_budg
create table #Tree (link int,[level] int)

select @link_tree=link from ro_svod_tree where link_report_org=@link_org and link_report_budg=@link_budg
declare @link_treeOwn int
set @link_treeOwn=@link_tree
insert #TREE
select A.link,0
 from report_svod_tree A
where A.link=(select top 1 link_self from ro_svod_tree where link=@link_tree)         
IF (select count(*) from #tree)=0
    insert #TREE
        select A.link,1
         from report_svod_tree A
        where A.link=@link_tree         

select @licount=0,@level=(select top 1 level from #tree)
while (select count(*) from #tree)<>@licount
    begin
        select @licount= count(*) from #tree
        insert #TREE
            select A.link,@level+1
            from report_svod_tree A
            where A.link_self in (select link from #tree where [level]=@level)
        set @level=@level+1
    end

delete #tree where level=0 

declare @col_kbk_doh int,@col_isp_doh int,@col_rosp_doh int,@col_kod_doh int
declare @col_kbk_rash int,@col_isp_rash int,@col_rosp_rash int,@col_kod_rash int
declare @col_kbk_ist int,@col_isp_ist int,@col_rosp_ist int,@col_kod_ist int

select @col_kbk_doh=link_col from report_coloumns where orders=1 and link_table=(select top 1 link_table from report_tables where link_form=@LF and orders=1)
select @col_kod_doh=link_col from report_coloumns where orders=2 and link_table=(select top 1 link_table from report_tables where link_form=@LF and orders=1)
select @col_isp_doh=link_col from report_coloumns where orders=4 and link_table=(select top 1 link_table from report_tables where link_form=@LF and orders=1)
select @col_rosp_doh=link_col from report_coloumns where orders=3 and link_table=(select top 1 link_table from report_tables where link_form=@LF and orders=1)

select @col_kbk_rash=link_col from report_coloumns where orders=1 and link_table=(select top 1 link_table from report_tables where link_form=@LF and orders=2)
select @col_kod_rash=link_col from report_coloumns where orders=2 and link_table=(select top 1 link_table from report_tables where link_form=@LF and orders=2)
select @col_isp_rash=link_col from report_coloumns where orders=4 and link_table=(select top 1 link_table from report_tables where link_form=@LF and orders=2)
select @col_rosp_rash=link_col from report_coloumns where orders=3 and link_table=(select top 1 link_table from report_tables where link_form=@LF and orders=2)

select @col_kbk_ist=link_col from report_coloumns where orders=1 and link_table=(select top 1 link_table from report_tables where link_form=@LF and orders=3)
select @col_kod_ist=link_col from report_coloumns where orders=2 and link_table=(select top 1 link_table from report_tables where link_form=@LF and orders=3)
select @col_isp_ist=link_col from report_coloumns where orders=4 and link_table=(select top 1 link_table from report_tables where link_form=@LF and orders=3)
select @col_rosp_ist=link_col from report_coloumns where orders=3 and link_table=(select top 1 link_table from report_tables where link_form=@LF and orders=3)

--select * from #tree
--select * from #tmp_calc164

while EXISTS(select * from #tree)
    begin
        select top 1 @link_tree=link from #tree
        select @link_org=link_report_org, @link_budg=link_report_budg from ro_svod_tree where link=@link_tree
        IF EXISTS( select * from #tmp_calc164 where kod_bp=(select top 1 budg from departments where link=@link_org)) 
            begin
                IF @link_tree=@link_treeOwn
                    begin
                        --отчет существует, просто почистим его
                        DELETE FROM report_dinamics where link_sf=@lsf
                        set @varKSLinkSF=@LSF
                    end
                    else
                    begin
                        DELETE FROM report_saved_forms where Link_Form = @LF and Period_Number = @PNomber and Period_Type = @pType and Begin_Date = @BDATE and Link_Organization = @Link_Org and isnull(Link_Type_Svod,0) = isnull(@Link_budg,0)
                        set @varKSLinkSF=0
                        exec I_REPORT_SAVE_FORM @varKSLinkSF output, @LF, 0, @BDAte, @pTYPE, @PNomber, @Link_Org, 0, default, default, default, default, default, default, default, @Link_budg, 0
                    end
--select  'пишем',@link_tree,@varKSLinkSF,@BDAte,@Link_budg
                INSERT REPORT_DINAMICS (link_sf,link_col,code_row,float_val)
                select link_sf,link_col,code_row,sum(float_val)
                    from (select @varKSLinkSF as link_sf,
                    case when type_kbk=1 then @col_rosp_doh 
                         when type_kbk=2 then @col_rosp_rash 
                         else @col_rosp_ist end as link_col
                    ,kbk as code_row,rosp as float_val from #tmp_calc164 where kod_bp=(select top 1 budg from departments where link=@link_org)) A
                     group by link_sf,link_col,code_row

                INSERT REPORT_DINAMICS (link_sf,link_col,code_row,float_val)
                select link_sf,link_col,code_row,sum(float_val)
                    from (select @varKSLinkSF as link_sf,
 case when type_kbk=1 then @col_isp_doh 
                         when type_kbk=2 then @col_isp_rash 
                         else @col_isp_ist end link_col
                    ,kbk as code_row,isp as float_val from #tmp_calc164 where kod_bp=(select top 1 budg from departments where link=@link_org)) A
                    group by link_sf,link_col,code_row

                INSERT REPORT_DINAMICS (link_sf,link_col,code_row,str_val)
                select distinct @varKSLinkSF,
                    case when type_kbk=1 then @col_kod_doh 
                         when type_kbk=2 then @col_kod_rash 
                         else @col_kod_ist end link_col
                    ,kbk as code_row,
                    case when type_kbk=1 then '010'
                         when type_kbk=2 then '200'
                         else '500' end as str_val 
                 from #tmp_calc164 where kod_bp=(select top 1 budg from departments where link=@link_org)
        
               IF @link_tree<>@link_treeOwn
                    begin
                        exec dbo.RO_CALCULATE_DOSCHET @varKSLinkSF
                    end

            end        

        delete #tree where link=@link_tree
    end





--UPDATE REPORT_OPTIONS SET val_int=@nastr  WHERE code='NEW_REPORT' 
   



GO


GRANT EXECUTE ON dbo.[RN_CALC_164] TO PUBLIC

GO



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

GO


CREATE                     PROCEDURE dbo.RN_F14KS  
  @varKScFormula  varchar(250),
  @varKScColumn    varchar(50),
  @varKSiLSF  int
 AS
print  @varKScFormula
print @varKScColumn
print @varKSiLSF
--коды строк  %10%
--print @varKScFormula
declare @Sign varchar(2),@LeftFormula varchar(200),@RightFormula varchar(200),@ibegin int,@iend int,@i int,@imax int,@formula_text varchar(200),
  @LeftFormulaNew varchar(200),@RightFormulaNew varchar(200),@linkForm int,@mes int,@info int,@cinfo varchar(200),@headerInfo int

declare @Cods table (kod varchar(10),calc int)
SET @info=0
--разбираем формулу
--ключевые слова
--%INFO% - информационное сообщение
--%MONTH% - число месяцев.
-- получим левую часть, правую часть и знак сравнения
set @formula_text=''
IF  CHARINDEX('#',@varKScColumn)>0
   begin
     set @formula_text=RIGHT(@varKScColumn,LEN(@varKScColumn)-CHARINDEX('#',@varKScColumn))
     set @varKScColumn=LEFT(@varKScColumn,CHARINDEX('#',@varKScColumn)-1)
   end
--select  @varKScColumn
SET @Sign=CASE
    WHEN CHARINDEX('<>',@varKScFormula)>0 THEN '<>'
    WHEN CHARINDEX('>=',@varKScFormula)>0 THEN '>='
    WHEN CHARINDEX('<=',@varKScFormula)>0 THEN '<='
    WHEN CHARINDEX('=',@varKScFormula)>0 THEN '='
    WHEN CHARINDEX('<',@varKScFormula)>0 THEN '<'
    WHEN CHARINDEX('>',@varKScFormula)>0 THEN '>'
    WHEN CHARINDEX('ТО',UPPER(@varKScFormula))>0 THEN '='
    ELSE ''
END
IF CHARINDEX('%INFO=',@varKScFormula)=0 
  BEGIN
    IF @Sign='' 
      RETURN -1
    ELSE
      BEGIN
        SET @LeftFormula=LEFT(@varKScFormula,CHARINDEX(@Sign,@varKScFormula)-1) 
        SET @RightFormula=SUBSTRING(@varKScFormula,CHARINDEX(@Sign,@varKScFormula)+LEN(RTRIM(@Sign)),LEN(@varKScFormula)-CHARINDEX(@Sign,@varKScFormula)-LEN(@Sign)+1)  
      END
  END
  ELSE
  BEGIN
    SET @LeftFormula=@varKScFormula
    SET @RightFormula=''
  END


--замена ключевых слов на значения
IF CHARINDEX('%MONTH%',@varKScFormula)>0 
  BEGIN
    SELECT @mes=MONTH(begin_date) From report_saved_forms Where link_saved_form=@varKSiLSF
    SET @varKScFormula=REPLACE(@varKScFormula,'%MONTH%',STR(@mes,2))    
    SET @LeftFormula=@varKScFormula
  END
IF CHARINDEX('%INFO=',@varKScFormula)>0 
  BEGIN
    SET @i=CHARINDEX('%INFO=',@varKScFormula)
    SET @cinfo=SUBSTRING(@varKScFormula,@i+6,
    CHARINDEX('%',@varKScFormula,@i+1)-@i-6)
    SET @varKScFormula=REPLACE(@varKScFormula,'%INFO='+@cinfo+'%','')   
    SET @info=1
    SET @LeftFormula=@varKScFormula
  END
--вытащим все коды в формулы
SET @ibegin=1
WHILE @ibegin<=LEN(@varKScFormula) and @ibegin>0 
  BEGIN
    SET @ibegin=CHARINDEX('%',@varKScFormula,@ibegin) 
    SET @iend=CHARINDEX('%',@varKScFormula,@ibegin+1) 
    IF @ibegin>0 and @iend>0 
      BEGIN
      INSERT @Cods select SUBSTRING(@varKScFormula,@ibegin+1,@iend-@ibegin-1),0 
      SET @ibegin=@iend+1
      END
      ELSE
        SET @ibegin=0
  END
--вытащим данные отчета
create table  #t_Form14n (Shifr  varchar(10), Kods varchar(50), GR3 numeric(20,2), GR4 numeric(20,2), GR5 numeric(20,2))
create table  #t_Form14 (Shifr  varchar(10), Kods varchar(50), GR3 numeric(20,2), GR4 numeric(20,2), GR5 numeric(20,2))
SELECT @linkForm=link_form From report_saved_forms Where link_saved_form=@varKSiLSF

INSERT #t_form14N 
SELECT LEFT(Code_Row, CHARINDEX('#', Code_Row) - 1) SHIFR,RIGHT(Code_Row, LEN(Code_Row) - CHARINDEX('#', Code_Row)) kods,float_val GR3,0 GR4,0 GR5 FROM REPORT_DINAMICS_ALL WHERE link_sf=@varKSiLSF AND link_col in (SELECT link_col FROM Report_coloumns WHERE orders=3 AND link_table in (SELECT link_table FROM report_tables WHERE link_form=@linkForm))
UNION 
SELECT LEFT(Code_Row, CHARINDEX('#', Code_Row) - 1) SHIFR,RIGHT(Code_Row, LEN(Code_Row) - CHARINDEX('#', Code_Row)) kods,0 GR3,float_val GR4,0 GR5 FROM REPORT_DINAMICS_ALL WHERE link_sf=@varKSiLSF AND link_col in (SELECT link_col FROM Report_coloumns WHERE orders=4 AND link_table in (SELECT link_table FROM report_tables WHERE link_form=@linkForm))
UNION 
SELECT LEFT(Code_Row, CHARINDEX('#', Code_Row) - 1) SHIFR,RIGHT(Code_Row, LEN(Code_Row) - CHARINDEX('#', Code_Row)) kods,0 GR3,0 GR4,float_val GR5 FROM REPORT_DINAMICS_ALL WHERE link_sf=@varKSiLSF AND link_col in (SELECT link_col FROM Report_coloumns WHERE orders=5 AND link_table in (SELECT link_table FROM report_tables WHERE link_form=@linkForm))

INSERT #t_form14
SELECT shifr,kods,sum(gr3) gr3,sum(gr4) gr4,sum(gr5) gr5 FROM #t_Form14n GROUP BY shifr,kods

--create table  #t_Form14N (Shifr  varchar(10), KBK varchar(50), [Table] char(2), Kods varchar(50), Name varchar(250), GR3 numeric(20,2), GR3_Name varchar(250), GR3_Formula varchar(250), GR4 numeric(20,2), GR4_Name varchar(250), GR4_Formula varchar(250), GR5 numeric(20,2), GR5_Name varchar(250), GR5_Formula varchar(250), Table_Name tinyint default(0))
--select * from #t_form14

create table  #t_resultF14  (LeftR float,RightR float)

INSERT #t_resultF14 select 0,0

--insert #t_form14 SELECT * FROM dbo.RO_FORM14(@varKSiLSF, DEFAULT, 0)  
--insert #t_form14 SELECT * FROM #t_form14N

--проверка
declare @kodnew varchar(100),@gr varchar(1),@nomErr int,@Kbk varchar(30),@cshifr varchar(5),@j int,@jmax int,@kod varchar(10),@value float,@ii int,@value1 float,@value2 float,@error int
select @nomErr=MAX(ORDERS) FROM #res 
SET @nomErr=ISNULL(@nomErr,1)
SELECT @imax=COUNT(DISTINCT SHIFR) FROM #t_form14
--print @imax
SET @i=1
--set ansi_warnings OFF
--SET ARITHABORT OFF
--SET ARITHIGNORE OFF
WHILE @i<=@imax
  BEGIN
--    SELECT TOP 1 @cshifr=SHIFR,@kbk=kbk FROM #t_form14
    SELECT TOP 1 @cshifr=SHIFR FROM #t_form14
    SET @ii=3
    WHILE @ii<=5 
      BEGIN
        IF (@varKScColumn=LTRIM(STR(@ii)) OR @varKScColumn='*' OR @varKScColumn='')
        BEGIN
        SELECT @jmax=COUNT(*) FROM @cods
        UPDATE @cods SET calc=0 
        SET @j=1  
        SET @LeftFormulaNew=@LeftFormula
        SET @RightFormulaNew=@RightFormula
        WHILE @j<=@jmax
           BEGIN
          SELECT TOP 1 @kod=RTRIM(kod),@kodnew=RTRIM(kod) FROM @cods WHERE calc=0
          UPDATE @cods SET calc=1 WHERE kod=@kod
          IF CHARINDEX('ГР',UPPER(@kod))>0
            BEGIN
              SET @gr=RIGHT(RTRIM(@kod),1)
              --print CHARINDEX('ГР',UPPER(@kod))
              SET @kodnew=LEFT(@kod,CHARINDEX('ГР',UPPER(@kod))-1)
              SET @ii=6
              --print 'гр'+@kod
            END
            ELSE    
              SET @gr=''
              SET @value=0
              IF ((@varKScColumn=LTRIM(STR(@ii)) OR @varKScColumn='*')  AND @ii=3) OR (@gr='3')
                SELECT TOP 1 @value=ISNULL(GR3,0) FROM #t_form14 WHERE RTRIM(kods)=@kodnew and SHIFR=@cSHIFR 
              IF ((@varKScColumn=LTRIM(STR(@ii)) OR @varKScColumn='*')  AND @ii=4)  OR (@gr='4')
                SELECT TOP 1 @value=ISNULL(GR4,0) FROM #t_form14 WHERE RTRIM(kods)=@kodnew and SHIFR=@cSHIFR 
              IF ((@varKScColumn=LTRIM(STR(@ii)) OR @varKScColumn='*')  AND @ii=5)  OR (@gr='5')
                SELECT TOP 1 @value=ISNULL(GR5,0) FROM #t_form14 WHERE RTRIM(kods)=@kodnew and SHIFR=@cSHIFR 
              SET @LeftFormulaNew=REPLACE(@LeftFormulaNew,'%'+@kod+'%',RTRIM(LTRIM(STR(@value,15,2))))              
              SET @RightFormulaNew=REPLACE(@RightFormulaNew,'%'+@kod+'%',RTRIM(LTRIM(STR(@value,15,2))))              

            SET @j=@j+1
          
            END

IF @info=0 
  BEGIN
--          print @LeftFormulaNew
--          print @RightFormulaNew    
          Execute('UPDATE #t_resultF14 SET LeftR='+@LeftFormulaNew)
          Execute('UPDATE #t_resultF14 SET RightR='+@RightFormulaNew)
          SELECT @value1=LeftR,@value2=RightR FROM #t_resultF14
          SET @value1=ISNULL(@value1,0)
          SET @value2=ISNULL(@value2,0)
          SET @error=0
          if @sign = '='
            if abs(@Value1 - @Value2) > 0.0001
              SET @error=1                  
          if @sign = '>'
            if @Value1 - @Value2 < 0.0001
              SET @error=2                  
          if @sign = '<'
            if @Value2 - @Value1 < 0.0001
              SET @error=3                  
          if @sign = '>='
            if @Value1 - @Value2 < -0.0001
              SET @error=4
          if @sign = '<='
            if @Value2 - @Value1 < -0.0001
              SET @error=5
          if @sign = '<>'
            if abs(@Value2 - @Value1) < 0.0001
              SET @error=6
          if @sign = 'ТО'
            if abs(@Value2 - @Value1) < 0.0001
              SET @error=7

          IF @error>0
            begin
              set @ii=@ii
              set @nomErr=@nomErr+2
              SELECT @kbk=RTRIM(RTRIM(Razd_Code)+' '+RTRIM(Cel_st_code)+' '+RTRIM(Vr_code)) FROM REPORT_FORM14_RAZD_NAME WHERE Shifr=@cShifr
			 IF @ii<>6
              insert #Res(orders, res, cdoc, ccol, ckod)
              select 3+@nomErr, '-',case  when @formula_text='' then REPLACE(RTRIM(@varKscFormula),'%','"') else  @formula_text end + ' КБК:'+@kbk+', Шифр строки:'+RTRIM(@cShifr), case when @varKScColumn='*'  then '№'+LTRIM(STR(@ii)) when @varKScColumn<>'' then '№'+@varKScColumn else '' end,case  when @formula_text='' then  @LeftFormulaNew+' '+@sign+' '+@RightFormulaNew else '' end 
			 IF @ii=6
              insert #Res(orders, res, cdoc, ccol, ckod)
              select 3+@nomErr, '-',case  when @formula_text='' then REPLACE(RTRIM(@varKscFormula),'%','"') else  @formula_text end + ' КБК:'+@kbk+', Шифр строки:'+RTRIM(@cShifr), '',case  when @formula_text='' then  @LeftFormulaNew+' '+@sign+' '+@RightFormulaNew else '' end 
            end
--info=0
  END
  ELSE
  BEGIN
          Execute('UPDATE #t_resultF14 SET LeftR='+@LeftFormulaNew)
          SELECT @value1=LeftR FROM #t_resultF14
          SET @value1=ISNULL(@value1,0)
          set @ii=@ii
          IF @value1<>0 
          BEGIN
            SELECT @HeaderInfo=orders from #res WHERE res='ИНФОРМАЦИЯ'
            IF @HeaderInfo is null 
              BEGIN
              --insert #Res(orders, res)
              --select 3+@nomErr, '-'
              set @nomErr=@nomErr+2
              insert #Res(orders, res)
              select 4+@nomErr,'-'
              insert #Res(orders, res)
              select 5+@nomErr,'ИНФОРМАЦИЯ'
              --insert #Res(orders, res)
              --select 5+@nomErr, '-'
              set @nomErr=@nomErr+4
              END
            set @nomErr=@nomErr+1
            SELECT @kbk=RTRIM(RTRIM(Razd_Code)+' '+RTRIM(Cel_st_code)+' '+RTRIM(Vr_code)) FROM REPORT_FORM14_RAZD_NAME WHERE Shifr=@cShifr
            insert #Res(orders, res, cdoc)
            select 3+@nomErr, '-', @cinfo+LTRIM(STR(@value1,15,4))+' Графа:'+LTRIM(str(@ii))+' КБК:'+RTRIM(@kbk)
          END

set @i=@i
  END

        END
      SET @ii=@ii+1
      END
    DELETE #T_Form14 WHERE SHIFR=@cShifr  
    SET @i=@i+1
  END
--set ansi_warnings ON
--SET ARITHABORT ON
--SET ARITHIGNORE ON

drop table #t_form14
drop table #t_form14n
drop table #t_resultF14 
select 0 as val


GO


GRANT EXECUTE ON dbo.[RN_F14KS] TO PUBLIC

GO


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

GO
-- Установка настроек плана счетов на КОСГУ --
CREATE PROCEDURE dbo.XK_NASTR_S_ACCOUNTS_KOSGU
	(
	@intLINK_ACCT	INT = NULL,
	@BUF_NAME	VARCHAR (100) = '',
	@iTYPE_REC		TINYINT = 0,
	@intDEP_LINK	INT = NULL
	)

AS
BEGIN
	SET @BUF_NAME = ISNULL (@BUF_NAME, '')
	

	UPDATE SA_SGU
	SET
		COMMENT = CONVERT (VARCHAR (254), LTRIM (SA_SGU_NASTR.[NAME]))
	FROM dbo.S_ACCOUNTS_SGU SA_SGU
	INNER JOIN dbo.S_ACCOUNTS SA ON	(SA.LINK = SA_SGU.ACCOUNT)
	INNER JOIN dbo.KOSGU ON (KOSGU.LINK = SA_SGU.LINK_SGU)
	INNER JOIN dbo.S_ACCOUNTS_NASTR_KOSGU SA_SGU_NASTR ON
		(
		SA_SGU_NASTR.SINTH = SA.cSINTH
		AND SA_SGU_NASTR.ANALITH = SA.cANALIT
		AND SA_SGU_NASTR.SGU = KOSGU.CODE
		)
	LEFT JOIN dbo.S_ACCOUNTS_NEW_CONV BUF ON (BUF.BUF_NAME = @BUF_NAME
		AND BUF.SINTH_NEW = SA_SGU_NASTR.SINTH
		AND BUF.ANALITH_NEW = SA_SGU_NASTR.ANALITH
		)
	WHERE
		(@intLINK_ACCT IS NULL AND @BUF_NAME = ''
		OR @intLINK_ACCT IS NOT NULL AND SA_SGU.ACCOUNT = @intLINK_ACCT AND @BUF_NAME = ''
		OR @intLINK_ACCT IS NULL AND @BUF_NAME <> '' AND BUF.BUF_NAME = @BUF_NAME)
		AND BUF.TYPE_ACCT = @iTYPE_REC

	INSERT INTO dbo.S_ACCOUNTS_SGU 
		(
		ACCOUNT,
		LINK_SGU,
		COMMENT
		)
	SELECT
		SA.LINK,
		KOSGU.LINK,
		SA_SGU_NASTR.[NAME]
	FROM dbo.S_ACCOUNTS_NASTR_KOSGU SA_SGU_NASTR 
	INNER JOIN
		(
		SELECT '1' AS CODE UNION ALL SELECT '2' 
		UNION ALL 
		SELECT '3' UNION ALL SELECT '4' 
		) AS T111 ON (SA_SGU_NASTR.SINTH LIKE '50%'
						AND LEFT (SA_SGU_NASTR.ANALITH, 1) <> '9'
					OR T111.CODE = '1')
	INNER JOIN dbo.S_ACCOUNTS SA ON
		(
		SA.cSINTH = SA_SGU_NASTR.SINTH
		AND (
			SA_SGU_NASTR.SINTH LIKE '50%'
			AND SA_SGU_NASTR.ANALITH <> ''
			AND SA_SGU_NASTR.ANALITH <> '00'
			AND SA.cANALIT = (T111.CODE + RIGHT (SA_SGU_NASTR.ANALITH, 1))
			OR SA.cANALIT = SA_SGU_NASTR.ANALITH
			)
		)
	INNER JOIN dbo.KOSGU ON (KOSGU.CODE = SA_SGU_NASTR.SGU)
	LEFT JOIN dbo.S_ACCOUNTS_NEW_CONV BUF ON (BUF.BUF_NAME = @BUF_NAME
		AND BUF.SINTH_NEW = SA_SGU_NASTR.SINTH
		AND BUF.ANALITH_NEW = SA_SGU_NASTR.ANALITH
		)
	WHERE
		(@intLINK_ACCT IS NULL AND @BUF_NAME = ''
		OR @intLINK_ACCT IS NOT NULL AND SA.LINK = @intLINK_ACCT AND @BUF_NAME = ''
		OR @intLINK_ACCT IS NULL AND @BUF_NAME <> '' AND BUF.BUF_NAME = @BUF_NAME)
		AND BUF.TYPE_ACCT = @iTYPE_REC
		AND NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_SGU SA_SGU1 
						WHERE SA_SGU1.ACCOUNT = SA.LINK
							AND SA_SGU1.LINK_SGU = KOSGU.LINK
						)
	RETURN 0
END



GO


GRANT EXECUTE ON dbo.[XK_NASTR_S_ACCOUNTS_KOSGU] 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'	OR @intBUH_TYPE = 1
			SET @intMAX_KVD = 1
		ELSE
			SET @intMAX_KVD = 7
			
		-- Для настройки 500 раздела ПС --
		IF @ZABALANCE = 0 AND @SINTH LIKE '50%' AND @ANALIT <> '00' AND @ANALIT <> '' AND LEFT (@ANALIT, 1) = '0'
			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.[XI_CREATE_TEST_REC_FUNC]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[XI_CREATE_TEST_REC_FUNC]

GO

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

CREATE                              PROCEDURE [dbo].XI_CREATE_TEST_REC_FUNC
	@varKSTable	varchar(255) = ''
AS
SET @varKSTable = REPLACE(@varKSTable, '[dbo].[', '')
SET @varKSTable = REPLACE(@varKSTable, ']', '')
if coalesce(object_id(@varKSTable),0) = 0  
BEGIN
	PRINT 'Неверно указано имя таблицы:'
	PRINT @varKSTable
	RETURN 1
END

declare @varKSname sysname,
	@varKSshort_name	varchar(128)	
SET @varKSshort_name = 'RELATED_LIST_' + RTRIM(@varKSTable)
SET @varKSname = 'dbo.RELATED_LIST_' + RTRIM(@varKSTable)

-- Если не установлено Ext Properties, то не переформируем 
IF not exists (SELECT * FROM ::fn_listextendedproperty ('NOSCRIPT', 'user', 'dbo', 'function', @varKSshort_name, default, default))
	and object_id(@varKSshort_name) is not null
BEGIN
	print 'Функция ' + rtrim(@varKSname) + ' не является автоформируемой.'
	print 'Проверьте наличие свойства NOSCRIPT'
	RETURN 1
END

DECLARE @varKSType1	varchar(20),
	@varKSType2	varchar(20),
	@varKSType3	varchar(20)

SET @varKSType1 = 'Check data'	
SET @varKSType2 = 'CASCADE'		
SET @varKSType3 = 'Nullable'		


set nocount on

print @varKSTable + ' - Проверка на существование связей у таблицы'
if  isnull((select  count(*)
	from sysreferences A, syscolumns C, syscolumns E
	where A.rkey1=C.colid and A.rkeyid=C.id 
		and A.fkey1=E.colid and A.fkeyid=E.id 
		and object_name(A.rkeyid) = @varKSTable),0) = 0
BEGIN
	PRINT '	Связи отсутсвуют, функция не создана'
	RETURN 0
END


print '	Автоформирование функции проверки связанных записей'
DECLARE Constr CURSOR  STATIC LOCAL FOR
select  Con=object_name(A.constid),
	r_tab=object_name(A.rkeyid), 
	r_col=quotename(C.Name), 
	f_tab=Object_Name(A.fkeyid),
	f_col='T1.'+quotename(E.Name),
	E.isnullable,
	OBJECTPROPERTY(A.constid, 'CnstIsDisabled') as IsChecked,
	OBJECTPROPERTY(A.constid, 'CnstIsDeleteCascade') as IsDelCascade
from sysreferences A, syscolumns C, syscolumns E
where A.rkey1=C.colid and A.rkeyid=C.id 
	and A.fkey1=E.colid and A.fkeyid=E.id 
	and object_name(A.rkeyid) = @varKSTable 
ORDER BY 2,4,5

DECLARE 
	@varKSPTab	varchar(100),
	@varKSFTab	varchar(100),
	@varKSPCol	varchar(100),
	@varKSFCol	varchar(100),
	@varKSCon	varchar(100),
	@varKSPTabOLD	varchar(100),
	@varKSSQL		varchar(8000),
	@varKSSQLCONSTR	varchar(8000),
	@varKSSTRCONTROL	varchar(8000),
	@varKSlNull		bit,
	@varKSlCheck		bit,
	@varKSlCascDel	bit,
	@varKSlUpdate	bit,
	@varKSiCount		smallint

Declare @varKSidtab int,
	@varKScLinkFiled	sysname,
	@varKSiPKCount	int,
	@varKScDescr		varchar(8000),
	@varKScFromAdd		varchar(8000),
	@varKScWhereAdd		varchar(8000),
	@varKScPK_Name	sysname,
	@varKScPK1		sysname,
	@varKScPK2		sysname,
	@varKScPK3		sysname

SET @varKScDescr = ''
create table #tmp(text varchar(8000), id int identity(1,1))
IF OBJECT_ID(@varKSname) is null
	SET @varKSSQL='CREATE '	
ELSE
	SET @varKSSQL='ALTER '	
SET @varKSSQL='

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


' + @varKSSQL+'FUNCTION ' +RTRIM(@varKSname) + ' (@varKSiLink int, @varKSiMode smallint =7)
	RETURNS @varKSRET TABLE(
		LINK	INT,
		LINK2	INT,
		LINK3	INT,
		TABLE_NAME	varchar(128),
		TYPE	TINYINT,
		TYPE_STR	varchar(50),
		STR_WARNING	varchar(250),
		exec_link	INT,
		exec_object	varchar(128)
	)
/* TYPE - тип связи:
	1 - Check data	- Не позволяют удалить
	2 - Cascade	- Каскадно удаляются
	3 - Nullable	- Сбрасываются в Null
  @varKSiMode - битовая маска для поля TYPE - выводить ли соответствующие записи
*/
AS
-- Процедурa сформирована с помощью XI_CREATE_TEST_REC_FUNC 
--'+LTRIM(convert(char, getdate()))+'
BEGIN
IF @varKSiMode = 0 /* По умолчанию выводим все виды связей */
	SET @varKSiMode = 7 

INSERT INTO @varKSRET
'
	Insert into #tmp(text)
	Values (@varKSsql)

SET @varKSiCount = 0
OPEN Constr
FETCH NEXT FROM  Constr INTO @varKSCon, @varKSPTab, @varKSPCol, @varKSFTAb, @varKSFCol, @varKSlNull, @varKSlCheck, @varKSlCascDel
WHILE @@FETCH_STATUS=0
BEGIN
	
	
	Set @varKSidtab = object_id(@varKSFTAb)
	
	DECLARE PK_List CURSOR  STATIC LOCAL FOR
		SELECT scol.name 
		From sysobjects me
			inner join sysconstraints sc on me.id = sc.constid and me.xtype = 'PK' and sc.id = @varKSidtab
			inner JOIN sysindexes si on si.id = sc.id and si.name = object_name(sc.constid)
			inner join sysindexkeys sik on sik.id = sc.id and sik.indid = si.indid

			inner join syscolumns scol on scol.id = sik.id and scol.colid = sik.colid
		WHERE scol.name <> 'DATE_BEGIN' 

	SET @varKSiPKCount = 0
	SET @varKScPK1 = 'null'
	SET @varKScPK2 = 'null'
	SET @varKScPK3 = 'null'
	OPEN PK_List
	FETCH NEXT FROM  PK_List INTO @varKScPK_Name
	WHILE @@FETCH_STATUS=0
	BEGIN
		SET @varKSiPKCount = @varKSiPKCount + 1
		IF @varKSiPKCount = 1
			SET @varKScPK1 = 'T1.'+quotename(@varKScPK_Name)
		ELSE
			IF @varKSiPKCount = 2
				SET @varKScPK2 = 'T1.'+quotename(@varKScPK_Name)
			ELSE
				SET @varKScPK3 = 'T1.'+quotename(@varKScPK_Name)
		FETCH NEXT FROM  PK_List INTO @varKScPK_Name
	END

	CLOSE PK_List
	DEALLOCATE PK_List

	IF @varKSiCount = 0 
		SET @varKSSQL = ''
	ELSE
		SET @varKSSQL = '
	UNION
'

	IF @varKSiPKCount>1
		SET @varKSSQL = @varKSSQL + '
/* Несколько ключевых полей! */'
	IF @varKSiPKCount = 0
	BEGIN
		SET @varKScLinkFiled = @varKSFCol
		SET @varKSSQL = @varKSSQL + '
/* У таблицы отсутствуют ключевые поля! */'
	END
	
	SET @varKScDescr = ''
	SELECT @varKScDescr = query_add from s_tables where name = @varKSFTAb

	SET @varKScFromAdd = ''
	SELECT @varKScFromAdd = from_add from s_tables where name = @varKSFTAb

	SET @varKScWhereAdd = ''
	SELECT @varKScWhereAdd = where_add from s_tables where name = @varKSFTAb
	IF @varKScWhereAdd <> ''
		SET @varKScWhereAdd = @varKScWhereAdd + ' AND '

	IF coalesce(@varKScDescr,'') = ''
		SET @varKScDescr = 'left(''Зависимый объект из таблицы ' + @varKSFTAb + ''',250)  as str_warning,
		0 as exec_link,
		'''' as exec_object'

	IF @varKSlCheck = 0 and @varKSlCascDel = 0

		SET @varKSSQL = @varKSSQL + '
	--' + @varKSCon + '
	SELECT ' + rtrim(@varKScPK1) + ' as link, -- ' + rtrim(@varKScPK1) + '
		' + rtrim(@varKScPK2) + ' as link2, -- ' + rtrim(@varKScPK2) + '
		' + rtrim(@varKScPK3) + ' as link3, -- ' + rtrim(@varKScPK3) + '
	''' + rtrim(@varKSFTAb) + ''' as object, 
	1 as type,
	''Связанный'' as type_str, 
	' + rtrim(@varKScDescr) + ' 
	FROM ' + rtrim(@varKSFTAb) +' T1 '+@varKScFromAdd+'
	WHERE ' + @varKScWhereAdd + @varKSFCol + ' = @varKSiLink AND @varKSiMode&1 = 1'


	ELSE
	BEGIN

		IF @varKSlCheck = 1 and @varKSlNull=1 AND (@varKSFTab<>@varKSPTab OR @varKSPTab IN ('G_PROV1','G_PROV2'))

			SET @varKSSQL = @varKSSQL + '
	--' + @varKSCon + '
	select	' + rtrim(@varKScPK1) + ' as link, -- ' + rtrim(@varKScPK1) + '
		' + rtrim(@varKScPK2) + ' as link2, -- ' + rtrim(@varKScPK2) + '
		' + rtrim(@varKScPK3) + ' as link3, -- ' + rtrim(@varKScPK3) + '
	''' + rtrim(@varKSFTAb) + ''' as object, 
	3 as type, 
	''Необязательный'' as type_str, 
	' + rtrim(@varKScDescr) + ' 
	FROM ' + rtrim(@varKSFTAb) +' T1 '+@varKScFromAdd+'	
	WHERE '+ @varKScWhereAdd + @varKSFCol + ' = @varKSiLink AND @varKSiMode&4 = 4'

		ELSE

			SET @varKSSQL = @varKSSQL + '
	--' + @varKSCon + '
	select	' + rtrim(@varKScPK1) + ' as link, -- ' + rtrim(@varKScPK1) + '
		' + rtrim(@varKScPK2) + ' as link2, -- ' + rtrim(@varKScPK2) + '
		' + rtrim(@varKScPK3) + ' as link3, -- ' + rtrim(@varKScPK3) + '
	''' + rtrim(@varKSFTAb) + ''' as object, 
	2 as type, 
	''Подчиненный'' as type_str, 
	' + rtrim(@varKScDescr) + ' 
	FROM ' + rtrim(@varKSFTAb) +' T1 '+@varKScFromAdd+'
	WHERE '+ @varKScWhereAdd + @varKSFCol + ' = @varKSiLink AND @varKSiMode&2 = 2'

	END

	Insert into #tmp(text)
	Values (@varKSsql)

	SET @varKSSQL = ''
	SET @varKSiCount = @varKSiCount + 1
	FETCH NEXT FROM  Constr INTO @varKSCon, @varKSPTab, @varKSPCol, @varKSFTAb, @varKSFCol, @varKSlNull, @varKSlCheck, @varKSlCascDel
END

	Insert into #tmp(text)
	Values ('
RETURN
END
')

SET @varKSSQL = ''
--select text from #tmp order by id
IF @varKSiCount > 0  
begin
	--select text from #tmp order by id
	Declare @err int
	execute @err = dbo.ssp_execresultset 'select text from #tmp order by id'
	IF @@error <> 0 OR @err <> 0
	BEGIN
		select text from #tmp order by id
		RETURN
	END
end
ELSE
	print 'У таблицы [' + rtrim(@varKSTable) + '] нет подчиненных связей. Функция не создана!'

CLOSE ConStr
DEALLOCATE  ConStr
drop table #tmp

exec dbo.U_UPDATE_SCRIPT_PROPERTY @varKSshort_name, 1, 'NOSCRIPT'


GO


GRANT EXECUTE ON dbo.[XI_CREATE_TEST_REC_FUNC] TO PUBLIC

GO

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

GO





--[dbo].RS_REPORT_VIPISKA_FROM_ACCOUNT '20060518','20060518',67665




-- формирование выписки с лицевого счета 

CREATE           PROCEDURE dbo.RS_REPORT_VIPISKA_FROM_ACCOUNT
	@StartDate		datetime,
	@ENDDate		datetime,
	@var_link_acc		int

AS BEGIN


/*
DECLARE @startdate datetime, @ENDdate datetime, @var_link_acc int
SELECT @startdate='2005-01-01'
SELECT @ENDdate='2005-12-01' 
SET @var_link_acc=67665        
*/

DECLARE @our_acc varchar (20)

CREATE TABLE #Vipiska
(
 [buh_acc] 	int, 
 [s_acc] 	varchar (20),
 [d_acc]	varchar (20),
 [obj_code]	varchar (30),
 [name]		varchar (254),
 [number]	varchar(15),
 [date]		datetime,
 [summa_d]	numeric(19,2),
 [summa_k]	numeric(19,2),
 [db_kr]	tinyint,
 [kbk]		char(30),
 [ekr]		char(3),
) 

CREATE TABLE #Bik
([code] 	varchar(20),
 [bik]		varchar(9)
)

SELECT @our_acc = code FROM department_accounts
WHERE link = @var_link_acc

DECLARE @dep int
SET @dep = dbo.getowndeplink()


insert into #vipiska ([buh_acc], [s_acc], [d_acc], [OBJ_CODE], [name], [number], [date], [summa_d], [summa_k], [db_kr], [kbk], [ekr])
SELECT * 
FROM 
(
-- Выбираем платежные поручения по нашему счету
SELECT [buh_acc]=ap.account, [s_acc]=s_da.code, [d_acc]=d_da.code, [obj_code]=ob.code, ob.name, number, 
		g.date_prov, 0 as summa_d, G2.summa as summa_k, AP.db_kr, kbk=KBK.code, ekr=SGU.code
FROM dbo.G_PROV G
INNER JOIN dbo.S_OBJECTS OB ON OB.LINK = G.OBJECT 
	AND OB.CODE = 'DOCUMENTS_PAY'
INNER JOIN dbo.G_PROV1 G1 ON G1.LINK_UP = G.LINK
	AND G.DATE_Prov BETWEEN @startdate AND @ENDdate
INNER JOIN dbo.G_PROV2 G2 ON G2.LINK_UP = G1.LINK
INNER JOIN dbo.G_PROV_AP AP ON AP.LINK_UP = G2.LINK AND AP.ACCOUNT IN (SELECT link FROM s_accounts 
	WHERE code like '%.304.05%')
LEFT JOIN dbo.KOSGU SGU ON AP.EKR = SGU.LINK
LEFT JOIN dbo.KL_KBK KBK ON AP.KBK = KBK.LINK 
LEFT JOIN dbo.finanse_pays fp on g.link=fp.link
LEFT JOIN dbo.department_accounts s_da on s_da.link=fp.s_acc
LEFT JOIN dbo.department_accounts d_da on d_da.link=fp.d_acc
where fp.s_acc=@var_link_acc --and ap.db_kr=0


UNION

-- выбираем все документы (но не платежки) у которых в проводках есть счет 304.05 
-- а dep_acc = наш счет
SELECT [buh_acc]=ap.account, [s_acc]=null, [d_acc]=null, obj_code=ob.code, ob.name, number, date_prov, 
	[summa_d]=(CASE  WHEN (select s_active from s_accounts where link = AP.ACCOUNT)=1 THEN (CASE  WHEN ap.db_kr=0 THEN G2.summa ELSE -G2.summa END) ELSE 0 END),
	[summa_k]=(CASE  WHEN (select s_passive from s_accounts where link = AP.ACCOUNT)=1 THEN (CASE  WHEN ap.db_kr=1 THEN G2.summa ELSE -G2.summa END) ELSE 0 END), 
	AP.db_kr, kbk=KBK.code, ekr=SGU.code
FROM dbo.G_PROV G
INNER JOIN dbo.S_OBJECTS OB ON OB.LINK = G.OBJECT 
	AND OB.CODE <> 'DOCUMENTS_PAY'
INNER JOIN dbo.G_PROV1 G1 ON G1.LINK_UP = G.LINK
	AND G.DATE_prov BETWEEN @startdate AND @ENDdate
INNER JOIN dbo.G_PROV2 G2 ON G2.LINK_UP = G1.LINK
INNER JOIN dbo.G_PROV_AP AP ON AP.LINK_UP = G2.LINK AND AP.ACCOUNT IN (SELECT link FROM s_accounts 
	WHERE code like '%.304.05%')
LEFT JOIN dbo.KOSGU SGU ON AP.EKR = SGU.LINK
LEFT JOIN dbo.KL_KBK KBK ON AP.KBK = KBK.LINK
where ap.dep_acc=@var_link_acc


UNION

-- лимиты
SELECT [buh_acc]=ap.account, [s_acc]=Null, [d_acc]=Null, obj_code=ob.code, ob.name, number, date_prov, G2.summa as summa_d,0 as summa_k, AP.db_kr, kbk=KBK.code, ekr=SGU.code
FROM dbo.G_PROV G
INNER JOIN dbo.S_OBJECTS OB ON OB.LINK = G.OBJECT 
	AND OB.CODE in ('FINANS_LIMIT','FINANS_CC_LIMIT')
INNER JOIN dbo.G_PROV1 G1 ON G1.LINK_UP = G.LINK
	AND G.DATE_prov is not null
	AND G.DATE_prov BETWEEN @startdate AND @ENDdate
INNER JOIN dbo.G_PROV2 G2 ON G2.LINK_UP = G1.LINK
INNER JOIN dbo.G_PROV_AP AP 
	ON AP.LINK_UP = G2.LINK 
	AND (AP.ACCOUNT IN (SELECT link FROM s_accounts WHERE code like '%.501.15%') and ap.db_kr=0)
	AND EXISTS 
		(
		select * from g_prov_ap gpap 
		where (gpap.link_up=ap.link_up) and (gpap.ACCOUNT in (SELECT link FROM s_accounts WHERE code like '%.501.13%') and gpap.db_kr=1)
		)
LEFT JOIN dbo.KOSGU SGU ON AP.EKR = SGU.LINK
LEFT JOIN dbo.KL_KBK KBK ON AP.KBK = KBK.LINK
LEFT JOIN dbo.finanse_head fh on g.link=fh.link 
Where fh.account=@var_link_acc

) AS b 
ORDER BY obj_code




--Select * from #vipiska
--end

-- формируем таблицу соответсвия бик - код
INSERT INTO #BIK (code, bik)
select distinct code, bik from 
(
select code, bank_link from department_accounts where bank_link is not null
union all
select da.code, ta.bank_link from department_accounts DA left join treasury_accounts TA on DA.ta_link=TA.link
) A join banks ba on a.bank_link=ba.link

CREATE TABLE #TEMP
(
 [buh_acc] 	int, 
 [obj_name]	varchar (255),
 [date_doc]	datetime,
 [kor_acc]	varchar (20),
 [number]	varchar(15),
 [kbk]		char(30),

 [ekr]		char(3),
 [bud_class]    char(30),
 [debet]	numeric(19,2),
 [kredit]	numeric(19,2),
 [our_acc]	varchar (20),
 [d]		int
)
------------------------------------------------------------------------------------

insert into #temp
SELECT  
	 [buh_acc] =  v.buh_acc,
	 [obj_name]=case v.obj_code 
			When 'DOCUMENTS_PKO' THEN 'Расх.КО'
			When 'DOCUMENTS_PAY' THEN 'Пл.поруч.'
			When 'DOCUMENTS_INVOICE_ISSUED' THEN 'Счет-факт. выд.'
			When 'DOCUMENTS_INVOICE_RECEIVED' THEN 'Счет-факт.пол.'
			When 'DOCUMENTS_OPER' THEN 'Пр.опер.'
			When 'FINANS_LIMIT' THEN 'Лимит'		
			When 'FINANS_C_LIMIT' THEN 'Измен. лим.'
			When 'FINANS_ASSIGN' THEN 'Ассигн.'
			When 'FINANS_CONTRACT' THEN 'Договор'
			When 'SHABLON_DOCUMENTS_PROV' THEN 'Типов.опер.'
			ELSE name
			END, 
	[data_doc]=v.date,
	[kor_acc]=v.d_acc,
	v.number, v.kbk, v.ekr,
	[bud_class]=(case when v.kbk is null and v.ekr is null then ''
		   else rtrim(v.kbk)+'.'+v.ekr  END),
-- старый вариант
--	[debet]=(CASE  WHEN v.db_kr=1 THEN v.summa ELSE 0 END),
--	[kredit]=(CASE WHEN v.db_kr=0 THEN v.summa ELSE 0 END),
	[debet]= v.summa_d, --(CASE  WHEN (select s_active from s_accounts where link=v.buh_acc)=1 THEN (CASE  WHEN v.db_kr=0 THEN v.summa ELSE -v.summa END) ELSE 0 END),
	[kredit]= v.summa_k, --(CASE WHEN (select s_passive from s_accounts where link=v.buh_acc)=1 THEN (CASE  WHEN v.db_kr=1 THEN v.summa ELSE -v.summa END) ELSE 0 END),
	[our_acc]=@our_acc,
	d = v.db_kr
FROM #Vipiska v
order by date, obj_code
 
select t.*, b.bik 
from #temp t left join #bik b on kor_acc=code

DROP TABLE #Vipiska
DROP TABLE #temp
DROP TABLE #bik

END










GO


GRANT EXECUTE ON dbo.[RS_REPORT_VIPISKA_FROM_ACCOUNT] TO PUBLIC

GO




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

GO


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

CREATE      PROCEDURE [dbo].BK_REPORT_OV_F0511808
	@varKSDATE_BEGIN	DATETIME,	
	@varKSDATE_END	DATETIME,	
	@varKSnPRN_KBK	INT		,
	@varKSnPRN_SGU	INT		,
	@varKScVal1 char(1), @varKSnOtborLink1 int,
	@cVal_KBK char(1), @nOtborLinkKBK int	/* Отбор КБК */,
	@intSVOD_ZB INT		
AS
BEGIN
	DECLARE	@varKSLINK_DEP	INT		,
		@varKScNEXT_PERIOD	VARCHAR (10),
		@varKScBEGIN_PERIOD	VARCHAR (10),
		@varKScEND_PERIOD	VARCHAR (10),

		@varKSDEP_CODE	VARCHAR (20),
		@varKSDEP_NAME	VARCHAR (254),
		@varKSDEP_OKPO	VARCHAR (20),
		@varKSEMP_CODE	VARCHAR (20),
		@varKSEMP_NAME	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 @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 @varKSLINK_DEP = LINK,
		@varKSDEP_CODE = CODE,
		@varKSDEP_NAME = [NAME],
		@varKSDEP_OKPO = OKPO
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = COALESCE (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
*/
	/* -- Параметры организации -- */
	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
		SET @varKSDEP_NAME = RTRIM (@varKSDEP_NAME) + ' (ЦБ)'
	
	/* -- ОСВ -- */
	DECLARE @OSV TABLE (LINK_ACCT INT,
			SA_CODE VARCHAR (20),
			KBK INT, SGU INT,
			IN_SUMMA NUMERIC (28,2),	
			D_SUMMA NUMERIC (28,2),		
			K_SUMMA NUMERIC (28,2),		
			OUT_SUMMA NUMERIC (28,2)	
			)	

	INSERT INTO @OSV
	SELECT OSV.ACCOUNT,
		OSV.SA_CODE,
		CASE
			WHEN @varKSnPRN_KBK = 1 THEN OSV.KBK
			ELSE 0
		END,
		CASE
			WHEN @varKSnPRN_SGU = 1 THEN OSV.SGU
			ELSE 0
		END,
		SUM (OSV.IN_SUMMA),
		SUM (OSV.D_SUMMA),
		SUM (OSV.K_SUMMA),	
		SUM (OSV.OUT_SUMMA)
	FROM dbo.BK_GetTableOSVByDate (@varKSDATE_BEGIN, @varKSDATE_END, DEFAULT) OSV
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = OSV.ACCOUNT)
	INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = OSV.KBK)
	WHERE @intSVOD_ZB = 1
		OR (@intSVOD_ZB = 0 AND OSV.DEP_LINK = @varKSLINK_DEP)
	GROUP BY OSV.ACCOUNT,
		OSV.SA_CODE,
		CASE
			WHEN @varKSnPRN_KBK = 1 THEN OSV.KBK
			ELSE 0
		END,
		CASE
			WHEN @varKSnPRN_SGU = 1 THEN OSV.SGU
			ELSE 0
		END

	DECLARE @RESULT TABLE (BEGIN_P VARCHAR (10), END_P VARCHAR (10), NEXT_P VARCHAR (10),
			LINK_ACCT INT, SA_CODE VARCHAR (20),
			KBK INT, SGU INT,
			DEP_NAME VARCHAR (254), DEP_OKPO VARCHAR (20),
			ACCT_CODE VARCHAR (60), ACCT_NAME VARCHAR (254),
			DIN_SUM NUMERIC (28,2), KIN_SUM NUMERIC (28,2),
			D_SUMMA NUMERIC (28,2),				
			K_SUMMA NUMERIC (28,2),				
			DOUT_SUM NUMERIC (28,2), KOUT_SUM NUMERIC (28,2), 
			REP1 TINYINT
			)

	SET @varKScNEXT_PERIOD = CONVERT (VARCHAR (10), DATEADD (DAY, 1, @varKSDATE_END), 104)
	SET @varKScBEGIN_PERIOD = CONVERT (VARCHAR (10), @varKSDATE_BEGIN, 104)
	SET @varKScEND_PERIOD = CONVERT (VARCHAR (10), @varKSDATE_END, 104)

	INSERT INTO @RESULT
	SELECT @varKScBEGIN_PERIOD,
		@varKScEND_PERIOD,
		@varKScNEXT_PERIOD,
		OSV.LINK_ACCT,
		OSV.SA_CODE ,
		OSV.KBK,
		OSV.SGU,
		@varKSDEP_NAME,
		@varKSDEP_OKPO,
		dbo.BK_GetAcctFullCode1 (OSV.LINK_ACCT, OSV.KBK, OSV.SGU, @varKSnPRN_KBK, @varKSnPRN_SGU),
		SA.[NAME],
		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,			
		1
	FROM @OSV OSV
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.LINK_ACCT)

	SELECT * 
	FROM @RESULT
	WHERE (D_SUMMA <> 0)
		OR (K_SUMMA <> 0)
		OR (DIN_SUM <> 0)
		OR (KIN_SUM <> 0)
		OR (DOUT_SUM <> 0)
		OR (KOUT_SUM <> 0)
	ORDER BY SA_CODE, ACCT_CODE
	
END




GO


GRANT EXECUTE ON dbo.[BK_REPORT_OV_F0511808] TO PUBLIC

GO


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


GO

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

GO
/*

  © Кейсистемс (Keysystems), 2006
  Возвращает список атрибутов
*/


CREATE       PROCEDURE dbo.RT_GET_KBK_FOR_SELECTION
	@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 dbo.BI_DICTION_BUDG_TYPE where link = rsf.link_type_svod),
    rsf.link_type_svod
    from   dbo.report_saved_forms RSF (nolock) 
    where  RSF.link_form in (
		select rt2.link_form from BufferGetTableByID('REPORT_COL_LINK_CHECKED') rl2 
        inner join dbo.report_coloumns rc2 (nolock) on rc2.link_col = rl2.link 
        inner join dbo.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.del = 0
	and RSF.version = (
		select  top 1 version
		from dbo.report_saved_forms as lrsf (nolock) 
		where lrsf.link_form = RSF.link_form
      AND lrsf.del = 0
		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)
	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)

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 = 'Код расхода'
)
-----------------------------------------------------------------------------------------------------------------------
-------------------
exec DropTempTable '#code_row'
create table #code_row (code varchar(250)) -- табличка в которую будут помещены линки кодовых строк и соответсвующих КБК
-------------------
insert into #code_row  -- в этом кусочке в таблицу #code_row (см. выше) помещаются значения допускаемые фильтрами по КБК и Боковику. Причём из столбцов, не являющихся ключевыми
select distinct 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)
-------------------
insert into #code_row  -- в этом кусочке в таблицу #code_row (см. выше) помещаются значения допускаемые фильтрами по КБК и Боковику. Причём из столбцов, ЯВЛЯЮЩИХСЯ ключевыми
select distinct 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)
-------------------

insert into #code_row  -- здесь берём линки строк и значение КБК из таблицы report_formula
select distinct rf.formula
from 
    dbo.report_formula as rf 
    inner join @kbk_tab as kt
        on rf.link_col = kt.link_col
where 
    rf.formula not in (select code from #code_row)
and
    rf.link_row in (
        select rf2.link_row
        from
            dbo.report_formula as rf2
            inner join dbo.report_coloumns as rc
                on rf2.link_col = rc.link_col
            inner join dbo.report_tables as rt
                on rt.link_table = rc.link_table and rt.link_code_col = rc.link_col
    )

insert into #code_row -- здесь берём линки строк и значение КБК из таблицы report_string
select distinct rs.str_val
from 
    #sf as sf 
    inner join dbo.report_string 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 not in (select code from #code_row)
and
    rs.link_row in (
        select rf2.link_row
        from
            dbo.report_formula as rf2
            inner join dbo.report_coloumns as rc
                on rf2.link_col = rc.link_col
            inner join dbo.report_tables as rt
                on rt.link_table = rc.link_table and rt.link_code_col = rc.link_col
    )

-- select (case when isnull(sk.code,-1)=-1 then 0 else 1 end) as [checked], cr.code as [code], (select top 1 kbk.name from dbo.report_kbk as kbk where kbk.code = cr.code) as [name]
-- from 
--     #code_row as cr 
--     left join #SelectedKBK as sk
--         on cr.code = sk.code

create table #res (checked tinyint,code varchar(50),[name] varchar(250))

insert into #res
select 0 as checked, cr.code as [code], (select top 1 kbk.name from dbo.report_kbk as kbk where kbk.code = cr.code) as [name]
from 
    #code_row as cr 

update #res
set checked = 1
where code in (select code from #SelectedKBK)

select * from #res

drop table #res

exec DropTempTable '#code_row'


GO


GRANT EXECUTE ON dbo.[RT_GET_KBK_FOR_SELECTION] 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(10), 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(10), 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) + '<ФайлПФР xmlns="http://schema.pfr.ru">'
	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) + '<ФайлПФР xmlns="http://schema.pfr.ru">'
					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.[SAL_CHANGE_SFIN]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SAL_CHANGE_SFIN]

GO
CREATE PROC [dbo].SAL_CHANGE_SFIN
	@OLD_KBK_CODE	VARCHAR(30),
	@NEW_KBK_CODE	VARCHAR(30),
	@DATE		DATETIME,
	@OPT1		TINYINT = 0,
	@OPT2		TINYINT = 0,
	@OPT3		TINYINT = 0,
	@OPT4		TINYINT = 0,
	@TAB_EMPL	VARCHAR(10)
AS

BEGIN

	DECLARE @OLD_KBK_LINK INT, @NEW_KBK_LINK INT, @MSG VARCHAR(254), @LINK_EMPL INT
	
	SET @OLD_KBK_LINK = (SELECT TOP 1 LINK FROM dbo.SAL_SFIN WHERE CODE = @OLD_KBK_CODE)
	IF @OLD_KBK_LINK IS NULL
	BEGIN
		SET @MSG = 'Не найден в базе источник финансиорования с кодом' + @OLD_KBK_CODE
		PRINT @MSG
		RETURN 1
	END

	SET @NEW_KBK_LINK = (SELECT TOP 1 LINK FROM dbo.SAL_SFIN WHERE CODE = @NEW_KBK_CODE)
	IF @NEW_KBK_LINK IS NULL
	BEGIN
		SET @MSG = 'Не найден в базе источник финансиорования с кодом' + @NEW_KBK_CODE
		PRINT @MSG
		RETURN 1
	END
	
	SET @NEW_KBK_LINK = (SELECT TOP 1 LINK FROM dbo.SAL_SFIN WHERE CODE = @NEW_KBK_CODE)
	IF @NEW_KBK_LINK IS NULL
	BEGIN
		SET @MSG = 'Не найден в базе источник финансиорования с кодом' + @NEW_KBK_CODE
		PRINT @MSG
		RETURN 1
	END

	SET @LINK_EMPL = (SELECT TOP 1 LINK FROM dbo.EMPL WHERE TAB = @TAB_EMPL)
	IF @LINK_EMPL IS NULL
	BEGIN
		SET @MSG = 'Не найден в базе сотрудник с табельным номером' + @TAB_EMPL
		PRINT @MSG
		RETURN 1
	END
	
	IF @DATE IS NULL
	BEGIN
		SET @MSG = 'Не указана дата смены источника финансирования'
		PRINT @MSG
		RETURN 1
	END		

	DECLARE @RESULT INT

	EXECUTE @RESULT = [dbo].SAL_CHANGE_KBK 
		@OLD_KBK_LINK = @OLD_KBK_LINK,
		@NEW_KBK_LINK = @NEW_KBK_LINK,
		@DATE = @DATE,
		@OPT1 = @OPT1,
		@OPT2 = @OPT2,
		@OPT3 = @OPT3,
		@OPT4 = @OPT4,
		@LINK_EMPL = @LINK_EMPL

	IF @RESULT = 0
	BEGIN
		SET @MSG = 'Замена источника ' + @OLD_KBK_CODE + ' на ' + @NEW_KBK_CODE 
			 + ' c даты ' + CONVERT(VARCHAR(10), @DATE, 104) + ' для сотрудника ' + @TAB_EMPL
			 + ' успешно выполнена!'
		PRINT @MSG
		RETURN 0
	END	
	ELSE
	BEGIN
		PRINT 'Замена не выполнена!'
		RETURN 0
	END			
END


GO


GRANT EXECUTE ON dbo.[SAL_CHANGE_SFIN] 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', 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,
	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', 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,
	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', 30)
			+ 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', 30)
			+ 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', 30)
			+ 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', 30)
			+ 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', 30)
			+ 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', 30)
			+ 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

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

GO


CREATE                    PROCEDURE [dbo].X_OUTPUT_PAY
	@varKSintLINK	int
AS

Declare 
	@varKSintSKLINK	int,	
	@varKSintSKALINK	int,	
	@varKSintSKBLINK	int,	

	@varKSintDKLINK	int,	
	@varKSintDBLINK	int,	
	@varKSintDKALINK	int,	
	@varKSintDKBLINK	int,	

	@varKSintDRSLINK	int,	
	@varKSintDLSLINK	int,
	@varKScNumber_bo varchar(10),
	@varKScDoh_code varchar(30),
	@varKScSGU_code varchar(3)

Select  

	@varKSintSKLINK = CASE WHEN DA_S.[TYPE_NAME] <> 'расчетный' THEN DA_S.REF_LINK_K ELSE NULL END,
	@varKSintSKALINK = CASE WHEN DA_S.[TYPE_NAME] <> 'расчетный' THEN DA_S.K_ACC_LINK ELSE NULL END,

	@varKSintDBLINK = CASE WHEN DA_D.[TYPE_NAME] = 'расчетный' THEN DA_D.REF_LINK_B ELSE NULL END,
	@varKSintDKLINK = CASE WHEN DA_D.[TYPE_NAME] <> 'расчетный' THEN DA_D.REF_LINK_K ELSE NULL END,

	@varKSintDKALINK = CASE WHEN DA_D.[TYPE_NAME] <> 'расчетный' THEN DA_D.K_ACC_LINK ELSE NULL END,
	@varKSintDRSLINK = CASE WHEN DA_D.[TYPE_NAME] = 'расчетный' THEN D_ACC_LINK ELSE NULL END,
	@varKSintDLSLINK = CASE WHEN DA_D.[TYPE_NAME] <> 'расчетный' THEN D_ACC_LINK ELSE NULL END

From DOCUMENTS_PAY DP
INNER JOIN DICTIONARY_ACCOUNTS DA_S ON DA_S.LINK = S_ACC_LINK 
INNER JOIN DICTIONARY_ACCOUNTS DA_D ON DA_D.LINK = D_ACC_LINK 
Where DP.LINK = @varKSintLINK

Select @varKSintSKBLINK = (Select BANK_LINK From Dictionary_K_Accounts Where LINK = @varKSintSKALINK)


select * into #documents_pay from documents_pay PAY Where link = @varKSintLINK


DECLARE 
	@varKSINN_OK_RCP VARCHAR(254), @varKSNM_OK_RCP VARCHAR(254),
	@varKSRS_RCP VARCHAR(254), 	@varKSLS_RCP VARCHAR(254), 
	@varKSBIK_RCP VARCHAR(254), @varKSBANK_RCP VARCHAR(254),
	@varKSKS_RCP VARCHAR(254), @varKSFILIAL_RCP VARCHAR(50)
  DECLARE 
    @varKSINN_OK_PAY0 BIT, @varKSNM_OK_PAY0 BIT, @varKSFILIAL_PAY0 BIT, 
    @varKSINN_OK_RCP0 BIT, @varKSNM_OK_RCP0 BIT, @varKSLS_RCP0 BIT, @varKSFILIAL_RCP0 BIT, 
    @varKSTIME_PAY0 BIT, @varKSKOD_FP0 BIT, @varKSLEN_PURP INT

DECLARE @varKSPURPOSE VARCHAR(801), @varKSFULL_BANK BIT, @iBankCity bit, @varKSNAME_PAY VARCHAR(512), @varKSNAME_RCP VARCHAR(512)
  SELECT 
    @varKSLEN_PURP = ISNULL(LEN_PURP, 1)
  FROM 
    DOCUMENTS_PAY_OPTIONS2
  
  SELECT @varKSFULL_BANK = ISNULL(FULLBANK, 0),@iBankCity = ISNULL(BANK_CITY, 0) FROM DOCUMENTS_PAY_OPTIONS
  --SELECT  @varKSPURPOSE = LTRIM(RTRIM(dbo.PrintPlatporGetNaznPlat1(@varKSintLINK)))
  SELECT	@varKSNAME_PAY = dbo.BB_DEP_NAME_FOR_SHABLON(isnull(APO.SHABLON_D,APOD.SHABLON_D), default, P.S_ACC_LINK), 
			@varKSNAME_RCP = dbo.BB_DEP_NAME_FOR_SHABLON(CASE WHEN DOH_CODE is not null or P.OKATO is not null or P_REASON is not null or P.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), 
			@varKSPURPOSE = 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))
	FROM dbo.DOCUMENTS_PAY P
	inner join dbo.DOCUMENTS_PAY_ADD PA on P.LINK = PA.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
	where P.LINK = @varKSintLINK and P.S_ACC_TYPE = DA.TYPE
  
  SELECT @varKSPURPOSE = CASE WHEN LEFT(@varKSPURPOSE, 1) = CHAR(10) THEN RIGHT(@varKSPURPOSE, LEN(@varKSPURPOSE) - 1 ) ELSE @varKSPURPOSE END


IF @varKSintDLSLINK IS NOT NULL BEGIN 
	
	Select @varKSintDKBLINK = BANK_LINK 
	From Dictionary_K_Accounts 
	Where LINK = @varKSintDKALINK

	SELECT @varKSINN_OK_RCP = INN, @varKSNM_OK_RCP = convert(varchar(120), NAME) 
	From DICTIONARY_TREASURY Where LINK = @varKSintDKLINK

	SELECT @varKSRS_RCP = CODE From Dictionary_K_accounts Where LINK = @varKSintDKALINK
	SELECT @varKSLS_RCP = CODE From Dictionary_accounts Where LINK = @varKSintDLSLINK
	SELECT 
		@varKSBIK_RCP = BIK,
		@varKSBANK_RCP = CONVERT(VARCHAR(50), rtrim(NAME) + ' ' + case @iBankCity when 1 then isnull(CITY,'') else '' end),
      		@varKSKS_RCP =  KS,
		@varKSFILIAL_RCP = FILIAL_NAME
	From Dictionary_Bank Where LINK = @varKSintDKBLINK
END	

IF @varKSintDRSLINK IS NOT NULL BEGIN	
	SELECT @varKSINN_OK_RCP = '', @varKSNM_OK_RCP = '', @varKSLS_RCP = ''
	SELECT @varKSRS_RCP = CODE From Dictionary_accounts Where LINK = @varKSintDRSLINK

	SELECT 
		@varKSBIK_RCP = BIK,
		@varKSBANK_RCP = CONVERT(VARCHAR(50), rtrim(NAME) + ' ' + case @iBankCity when 1 then isnull(CITY,'') else '' end),
      		@varKSKS_RCP =  KS,
		@varKSFILIAL_RCP = FILIAL_NAME

	From Dictionary_Bank Where LINK = @varKSintDBLINK
END




SELECT
	@varKSINN_OK_PAY0 = ISNULL(INN_OK_PAY, 0),
	@varKSNM_OK_PAY0 = ISNULL(NM_OK_PAY, 0),
	@varKSFILIAL_PAY0 = ISNULL(FILIAL_PAY, 0),
	@varKSINN_OK_RCP0 = ISNULL(INN_OK_RCP, 0),
	@varKSNM_OK_RCP0 = ISNULL(NM_OK_RCP, 0),
	@varKSLS_RCP0 = ISNULL(LS_RCP, 0),
	@varKSFILIAL_RCP0 = ISNULL(FILIAL_RCP, 0),
	@varKSTIME_PAY0 = ISNULL(TIME_PAY, 0),
	@varKSKOD_FP0 = ISNULL(KOD_FP, 0)
FROM DOCUMENTS_PAY_ADD2
WHERE LINK = @varKSintLINK

/*
DECLARE @varKSNAME_PAY VARCHAR(512), @varKSNAME_RCP VARCHAR(512), @varKSS_ACC_LINK INT, @varKSD_ACC_LINK INT
SELECT @varKSS_ACC_LINK = S_ACC_LINK, @varKSD_ACC_LINK = D_ACC_LINK 
FROM DOCUMENTS_PAY WHERE LINK = @varKSintLINK

DECLARE @varKSnNOTNalog INT


SET @varKSnNOTNalog = 
	(SELECT 
		LEN(ISNULL(DOH_CODE, '')) 
		+ LEN(ISNULL(STATUS, ''))
		+ LEN(ISNULL(OKATO, ''))
		+ LEN(ISNULL(P_REASON, ''))
		+ LEN(ISNULL(PERIOD, ''))
		+ LEN(ISNULL(TREBNUM, ''))
		+ CASE WHEN (ISNULL(ZERODATE, 0) = 1 AND TREBDATE IS NULL ) OR TREBDATE IS NOT NULL THEN 1 ELSE 0 END
		+ LEN(ISNULL(P_TYPE, ''))
	FROM DOCUMENTS_PAY_ADD PAY1 
	WHERE LINK = @varKSintLINK )
 
SET @varKSnNOTNalog = CASE WHEN @varKSnNOTNalog = 0 THEN 1 ELSE 2 END
--SELECT @varKSNAME_PAY = DEP_NAME FROM dbo.PrintPlatporGetAcctData(@varKSS_ACC_LINK, @varKSFULL_BANK, 0)
--SELECT @varKSNAME_RCP = DEP_NAME FROM dbo.PrintPlatporGetAcctData(@varKSD_ACC_LINK, @varKSFULL_BANK, @varKSnNOTNalog)

*/	


select
	PAY.link, 
	PAY.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] = S_INN,
	[KPP_PAY] = dbo.PrintPlatporGetKPP(@varKSintLINK, 0),
	[KOD_BP_PAY] = (Select BUDG From DICTIONARY_DEPARTMENT where link = S_LINK),
	[NAME_BP_PAY] = (Select convert(varchar(120), case when isnull(prefix, '') = '' then NAME else ltrim(rtrim(prefix)) + ' ' + ltrim(rtrim(name)) end ) From DICTIONARY_DEPARTMENT where link = S_LINK),
	[NAME_PAY] = @varKSNAME_PAY,
	[NUM_LS_PAY] = S_ACC_NUM,

	[KOD_TOFK_PAY] = (Select CODE From DICTIONARY_TREASURY Where link = @varKSintSKLINK),
	[INN_OK_PAY] = 
		CASE WHEN @varKSINN_OK_PAY0 = 1 THEN
			(Select INN From DICTIONARY_TREASURY Where link = @varKSintSKLINK)
		ELSE
			''
		END,
	[NM_OK_PAY] = 
		CASE WHEN @varKSNM_OK_PAY0 = 1 THEN 
			(Select convert(varchar(120), NAME) From DICTIONARY_TREASURY Where LINK = @varKSintSKLINK)
		ELSE
			''
		END,
	[RS_PAY] = (Select CODE From Dictionary_K_accounts Where LINK = @varKSintSKALINK),
	[BIK_PAY] = (Select BIK From Dictionary_Bank Where LINK = @varKSintSKBLINK),
	[BANK_PAY] = (Select convert(varchar(50), rtrim(NAME) + ' ' + case @iBankCity when 1 then isnull(CITY,'') else '' end) From Dictionary_Bank Where LINK = @varKSintSKBLINK),
    	[FILIAL_PAY] = 
		CASE 
			WHEN @varKSFILIAL_PAY0 = 1 THEN (Select convert(varchar(50), FILIAL_NAME) From Dictionary_Bank Where LINK = @varKSintSKBLINK) 
			ELSE '' 
		END,
	[KS_PAY] = (Select KS From Dictionary_Bank Where LINK = @varKSintSKBLINK),
	[INN_RCP]=D_INN,
	[KPP_RCP]=dbo.PrintPlatporGetKPP(@varKSintLINK, 1),

	[NAME_RCP]=@varKSNAME_RCP,

	[INN_OK_RCP]= CASE WHEN @varKSINN_OK_RCP0 = 1 THEN @varKSINN_OK_RCP ELSE '' END,
	[NM_OK_RCP] = CASE WHEN @varKSNM_OK_RCP0 = 1 THEN @varKSNM_OK_RCP ELSE '' END,
	[RS_RCP] = @varKSRS_RCP,
	[LS_RCP] = CASE WHEN @varKSLS_RCP0 = 1 THEN @varKSLS_RCP ELSE '' END,
	[BIK_RCP] = @varKSBIK_RCP,
	[BANK_RCP]= @varKSBANK_RCP,
	[FILIAL_RCP]= 
		CASE 
			WHEN @varKSFILIAL_RCP0 = 1 THEN @varKSFILIAL_RCP
			ELSE '' 
		END,
	[KS_RCP]=@varKSKS_RCP,

	[TIME_PAY] = CASE 
		WHEN @varKSTIME_PAY0 = 1 THEN srok 
		ELSE cast (null as datetime) END,

	[ORDER_PAY]=PAY.[ORDER],
	/*[PURPOSE] = LEFT(
			@varKSPURPOSE,
			CASE WHEN @varKSLEN_PURP = 1 THEN 800 WHEN @varKSLEN_PURP = 2 THEN 210 ELSE 800 END
			),*/
	[PURPOSE] = @varKSPURPOSE,
	[PRINT_KPP]='0',

	[PAYSTATUS] = PAY1.STATUS,
	[KBKD] = rtrim(ltrim(replace(PAY1.doh_code,'.',''))) + ltrim(PAY1.sgu_code),
	[PAYOKATO] = PAY1.OKATO,
	[OSNPLAT] = PAY1.P_REASON, 
	[NAL_PER] = PAY1.PERIOD,
	[N_DOK] = PAY1.TREBNUM, 
	[D_DOK] = CASE WHEN ISNULL(ZERODATE, 0) = 1 THEN '0' ELSE CONVERT(CHAR(10), PAY1.TREBDATE,104) END,
	[TYPE_PL] = PAY1.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 = @varKSintLINK 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 #documents_pay PAY
LEFT OUTER JOIN DOCUMENTS_PAY_ADD PAY1 ON PAY.LINK = PAY1.LINK


/*
-- бюджетные обязательства из договора
	select @varKScNumber_bo=fc.number_bo 
	from documents_pay dp, FINANS_CONTRACT_AND_CHANGES FC
	where  dp.dog_link=fc.link and dp.link = @varKSintLINK
*/

select top 1 @varKScNumber_bo = PAY.BO_NUM
from #documents_pay PAY	

-- Если платежка налоговая 
/*
  1. Если в проводочной части указана Доходная классификация то
   в блок PPST выгружаем код дохода = код дохода + сгу (20 символов)
   и сумму - больше ничего !
  2. Если в проводочной части указана Расходная классификация
   то выгружаем поблочно раздел, подраздел и т.д. .
   поле код дохода - пустой
*/

    select @varKScDoh_code = rtrim(ltrim(replace(doh_code,'.',''))) + ltrim(sgu_code)
	from documents_pay_add 
	where  link=@varKSintLINK

SELECT
	@varKSintLINK as link_up,	
	[MARKER] = 'PPST',
	[GLAVA] = LTRIM(RTRIM(ISNULL(F.CODE_FKR_M, ''))),
	[RAZDEL] =LTRIM(RTRIM(ISNULL(F.CODE_FKR_D, ''))),
	[STATIA] = LTRIM(RTRIM(ISNULL(F.CODE_FKR_T, ''))),
	[VID] = LTRIM(RTRIM(ISNULL(F.CODE_FKR_E, ''))),
--	[KOD_FP] = '',
	[KOD_FP] = convert(varchar(3), (select top 1 code from BD_DOP_CLASSIF BDC where BDC.link = GPA1.AP2)), 
	[E_KLASS] = LTRIM(RTRIM(ISNULL(KEK.CODE, ''))),
	[NUM_BO] =  LTRIM(RTRIM(ISNULL(@varKScNumber_bo,''))),
	[MON_FIN]='',
	[SUM_STR] = summa,
	[FOND_P] = '',

--	[KKIVNF] = convert(char(20),''), /* 2005.08 */
--	[KKIVF] = convert(char(20),''), /* 2005.08 */
--	[KDOH] = LTRIM(RTRIM(@varKScDoh_code)),	/* 2005.08 */


	[KKIVNF] = CASE 
				WHEN exists (select top 1 code from BI_DICTION_KBK where link = kbk and type = 8)
				THEN (REPLACE ((select top 1 code from BI_DICTION_KBK where link = kbk and type = 8),'.','') + isnull((select code from kosgu where link = SGU),''))
				end,

	[KKIVF] = CASE 
				WHEN exists (select top 1 code from BI_DICTION_KBK where link = kbk and type = 4)
				THEN (REPLACE ((select top 1 code from BI_DICTION_KBK where link = kbk and type = 4),'.','') + isnull((select code from kosgu where link = SGU),''))
				end,
	[KDOH] = CASE 
				WHEN exists (select top 1 code from BI_DICTION_KBK where link = kbk and type = 2)
				THEN (REPLACE ((select top 1 code from BI_DICTION_KBK where link = kbk and type = 2),'.','') + isnull((select code from kosgu where link = SGU),''))
				end,

	[ADD_KLASS] = (select top 1 code from BD_DOP_CLASSIF BDC where BDC.link = GPA1.AP2),	/* 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 G_PROV2 GP2 ON (GP1.LINK_UP = @varKSintLINK AND 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_VKR F ON GPA1.KBK = F.LINK_KBK
LEFT OUTER JOIN DICTIONARY_ITEM KEK ON GPA1.EKR = KEK.LINK





GO


GRANT EXECUTE ON dbo.[X_OUTPUT_PAY] TO PUBLIC

GO




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

GO

CREATE   PROCEDURE [dbo].SA_REP_ARCHE @LINK_DOC INT
AS

DECLARE @REF_ARHE INT

Select 
	NUM_ARHE,  
	[PER_ARHE],
	NAME_EMPL,
	TAB_NUMER,
	SYST_PAY = CASE WHEN SYST_PAY = 2 THEN 'Почасовая система оплаты' else '' END,
	DATE1, 	DATE2, 	ITOGO_DNI,
	NAME_TYP = NAME_TYP_ARHE,
	CODE_PAY, NAME_PAY,
	DATE_BEGIN,
	TYP_PERIOD = 'Расчёт ' + CASE TYP_PERIOD WHEN 1 THEN 'по текущему месяцу'
						 WHEN 2 THEN 'по 2 предыдущим месяцам'
						 WHEN 3 THEN 'по 12 предыдущим месяцам'
				end
from dbo.DOCUMENTS_ADD_ARCHE where LINK = @LINK_DOC

-- информация о предыдущих больничных по той же причине
SELECT 
	DI.link, DI.NUMBER, DI.NAME_EMPL,
	DI.[DAYS],	DI.DATE1, DI.DATE2, DI.CODE_TYP_ARHE, DI.NAME_TYP_ARHE,
	DI.CODE_PAYS, DI.NAME_PAYS, DI.KIDS_FLAG, DI.PERS_KID,
	DI.FAMILY_NAME,DI.PERS_LINK		
FROM DOCUMENTS_ADD_ARCHE da 
	 INNER JOIN DIS di ON di.ref_empl = da.ref_empl
					   AND di.ref_typ_arhe = da.ref_typ_arhe
					   AND di.link_pays = da.ref_pay
					   AND year(di.date1) = year(da.date1)
					   AND di.date1 < da.date1
WHERE da.link = @LINK_DOC
UNION ALL -- если ничего не найдено
Select link = 0, number = '', name_empl = '', [days] = 0, date1 = '', date1 = '', 
	   CODE_TYP_ARHE = '', NAME_TYP_ARHE = '', CODE_PAYS = '', NAME_PAYS = '', KIDS_FLAG = 0, 
	   PERS_KID = '', FAMILY_NAME = '', PERS_LINK = 0
WHERE NOT EXISTS(SELECT DI.*		
				 FROM DOCUMENTS_ADD_ARCHE da 
				 INNER JOIN DIS di ON di.ref_empl = da.ref_empl
					   AND di.ref_typ_arhe = da.ref_typ_arhe
					   AND di.link_pays = da.ref_pay
					   AND year(di.date1) = year(da.date1)
					   AND di.date1 < da.date1
				 WHERE da.link = @LINK_DOC)

---начисление по видам оплат
DECLARE @COUNT_M INT
SET @COUNT_M = COALESCE((Select COUNT(DISTINCT PERIOD) from SDOC_ADIS_TABLE2 where LINK_UP = @LINK_DOC),0)

SET @COUNT_M = CASE WHEN @COUNT_M = 0 THEN 1 ELSE @COUNT_M END

DECLARE @SCRIPT1 VARCHAR(8000), 
	@I INT, 
	@DATE_BEGIN_RP DATETIME,
	@RP_SUMMA_PREM NUMERIC(18,2),
	@RP_SUMMA NUMERIC(18,2),
	@SR_PREM NUMERIC(18,2),
	@RP_DAYS INT,
	@RP_HOURS NUMERIC(18,2),
	@RP_DAYS_N INT,
	@RP_HOURS_N NUMERIC(18,2),
	@SUMMA_BASE0 NUMERIC(18,2),
	@ITOGO_DNI NUMERIC(18,2),
	@ITOGO_CH NUMERIC(18,2),
	@INSTRUCT TINYINT

SELECT  @SCRIPT1 = '', @I = 1, @DATE_BEGIN_RP = DATE_BEGIN,
	@RP_SUMMA_PREM = RP_SUMMA_PREM, @RP_SUMMA = RP_SUMMA, 
	@SR_PREM = SR_PREM, @RP_DAYS = RP_DAYS, @RP_HOURS = RP_HOURS,
	@RP_DAYS_N = RP_DAYS_N, @RP_HOURS_N = RP_HOURS_N,
	@SUMMA_BASE0 = ROUND(SUMMA_BASE0, 2 ,0), @ITOGO_DNI = ITOGO_DNI, @ITOGO_CH = ITOGO_CH,
	@INSTRUCT = INSTRUCT
FROM dbo.DOCUMENTS_ADD_ARCHE where LINK = @LINK_DOC

IF EXISTS (SELECT * FROM dbo.SDOC_ADIS_TABLE3 where LINK_UP = @LINK_DOC) BEGIN

	WHILE @I <= @COUNT_M AND @I <= 12
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) 
				+ CASE WHEN @INSTRUCT = 1 
						THEN 
							' = ''' 
							+ CASE MONTH(DATEADD(MONTH,@I-1,@DATE_BEGIN_RP))
								WHEN 1 THEN 'Янв.'
								WHEN 2 THEN 'Фев.'
								WHEN 3 THEN 'Мар.'
								WHEN 4 THEN 'Апр.'
								WHEN 5 THEN 'Май.'
								WHEN 6 THEN 'Июн.'
								WHEN 7 THEN 'Июл.'
								WHEN 8 THEN 'Авг.'
								WHEN 9 THEN 'Сен.'
								WHEN 10 THEN 'Окт.'
								WHEN 11 THEN 'Ноя.'
								WHEN 12 THEN 'Дек.'
							END 
							+ CONVERT(VARCHAR(4),YEAR(DATEADD(MONTH,@I-1,@DATE_BEGIN_RP)))
							+ ''''
						ELSE 
							' = ''' + CONVERT(VARCHAR(4),YEAR(@DATE_BEGIN_RP)+@I-1) + 'г.'''
					END		
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = SUMMA' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))
		SET @I = @I + 1
	END

	SET @I = 1
	SET @SCRIPT1 = @SCRIPT1 + ', SUM_N = 0'
	WHILE @I <= @COUNT_M AND @I <= 12
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 + '+ COALESCE(SUMMA' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ',0)'
		SET @I = @I + 1
	END

	SET @SCRIPT1 = 'Select ORDERS, LINK_PAY, NAME_PAY = ISNULL(P.NAME,''Заработок у других работодателей'') , LINK_KBK, CODE_KBK = KBK.CODE' + @SCRIPT1 
			+ ' from dbo.SDOC_ADIS_TABLE3 T3 LEFT JOIN dbo.PAYS P ON T3.LINK_PAY = P.LINK '
			+ ' LEFT JOIN dbo.SAL_SFIN KBK ON T3.LINK_KBK = KBK.LINK WHERE LINK_UP = ' 
		+ CONVERT(VARCHAR(20),@LINK_DOC) + ' ORDER BY ORDERS'
	exec (@SCRIPT1)
END
ELSE	--Если рассчитывали исходя из МРОТ
	Select ORDERS = 0, LINK_PAY = 0, NAME_PAY = '', LINK_KBK = 0, CODE_KBK = '', ORDERS = 0, N_1 = '', S_1 = 0, SUM_N = 0

---начисление по месяцам
Select 
	ORDERS, 
	PERIOD = CASE WHEN @INSTRUCT = 1 THEN 
					+ CASE MONTH(PERIOD)
						WHEN 1 THEN 'Янв.'
						WHEN 2 THEN 'Фев.'
						WHEN 3 THEN 'Мар.'
						WHEN 4 THEN 'Апр.'
						WHEN 5 THEN 'Май.'
						WHEN 6 THEN 'Июн.'
						WHEN 7 THEN 'Июл.'
						WHEN 8 THEN 'Авг.'
						WHEN 9 THEN 'Сен.'
						WHEN 10 THEN 'Окт.'
						WHEN 11 THEN 'Ноя.'
						WHEN 12 THEN 'Дек.'
					END 
					+ CONVERT(VARCHAR(4),YEAR(PERIOD))
				ELSE
					CONVERT(VARCHAR(4),YEAR(PERIOD)) + 'г.'
			END	, 
	SUMMA, SUMMA_PREM, DAYS, HOURS, DAYS_N, HOURS_N, CODE_KBK = KBK.CODE, 
	RP_S_PREM = @RP_SUMMA_PREM, RP_SUMMA = @RP_SUMMA, 
	RP_DAYS = @RP_DAYS, RP_HOURS = @RP_HOURS,
	RP_DAYS_N = @RP_DAYS_N, RP_HOURS_N = @RP_HOURS_N,
	SR_PREM = @SR_PREM, DSUM = @SUMMA_BASE0
from SDOC_ADIS_TABLE2 T2  LEFT JOIN dbo.SAL_SFIN KBK ON T2.LINK_KBK = KBK.LINK
where link_up = @LINK_DOC
UNION ALL --Если рассчитывали исходя из МРОТ
Select 0, NULL, 0, 0, 0, 0, 0, 0, '', 0, 0, 0, 0, 0, 0, 0, 0
WHERE NOT EXISTS(SELECT * FROM dbo.SDOC_ADIS_TABLE2 WHERE link_up = @LINK_DOC)

---

Select @REF_ARHE = REF_DOC from dbo.SDOC_ADIS where LINK_UP = @LINK_DOC

DECLARE @CNT int, @TYP_CALC int, @DATE_R datetime, @DATE1 datetime, @DATE2 datetime
Select @CNT = CNT, @TYP_CALC = TYP_CALC, @DATE_R = DATE_R, @DATE1 = DATE1, @DATE2 = DATE2 from dbo.VAC_CHILD where LINK_R = @LINK_DOC

SET @CNT = COALESCE(@CNT,1)
SET @TYP_CALC = COALESCE(@TYP_CALC,2)

Select REF_ARHE = COALESCE(@REF_ARHE,0), [Name] = case when @CNT = 1 then 'Первый ребенок' else 'Второй или последующий ребенок' end, summa = ''
UNION ALL
Select REF_ARHE = COALESCE(@REF_ARHE,0), [Name] = 'Дата рождения ребенка', summa = convert(varchar(20), @DATE_R, 104)
UNION ALL
Select REF_ARHE = COALESCE(@REF_ARHE,0), [Name] = 'Начало оплаты', summa = convert(varchar(20), @DATE1, 104)
UNION ALL
Select REF_ARHE = COALESCE(@REF_ARHE,0), [Name] = 'Завершение оплаты', summa = convert(varchar(20), @DATE2, 104)
UNION ALL
Select REF_ARHE = COALESCE(@REF_ARHE,0), [Name] = 'Сумма выплачивается ' + case @TYP_CALC 
																when 2 then 'пропорционально рабочим дням'
																when 3 then 'пропорционально календарным дням'
																else 'без учета дней' 
																end, summa = ''
UNION ALL
Select REF_ARHE = COALESCE(@REF_ARHE,0), [Name] = 'Мин. размер пособия по уходу за 1 ребенком', summa = convert(varchar(20), dbo.sa_get_option_by_code('VAC_CHILD_OPT1')) where @CNT = 1
UNION ALL
Select REF_ARHE = COALESCE(@REF_ARHE,0), [Name] = 'Мин. размер пособия по уходу за 2 и более дет.', summa = convert(varchar(20), dbo.sa_get_option_by_code('VAC_CHILD_OPT2'))  where @CNT >= 2
UNION ALL
Select REF_ARHE = COALESCE(@REF_ARHE,0), [Name] = 'Макс. размер пособия по уходу за 1 ребенком', summa = convert(varchar(20), dbo.sa_get_option_by_code('VAC_CHILD_OPT3'))  where @CNT = 1
UNION ALL
Select REF_ARHE = COALESCE(@REF_ARHE,0), [Name] = 'Макс.  размер пособия по уходу за 2 и более дет.', summa = convert(varchar(20), dbo.sa_get_option_by_code('VAC_CHILD_OPT4'))  where @CNT >= 2
UNION ALL
Select REF_ARHE = COALESCE(@REF_ARHE,0), [Name] = 'Ср.м. число кал. дней для расчета пособ.', summa = convert(varchar(20), dbo.sa_get_option_by_code('VAC_CHILD_OPT5'))
UNION ALL
Select REF_ARHE = COALESCE(@REF_ARHE,0), [Name] = 'Процент заработка', summa = convert(varchar(20), dbo.sa_get_option_by_code('VAC_CHILD_OPT6'))

---начисление по больничному
Select ORDERS, DATE1, DATE2, SUM_LIMIT, DAYS, HOURS, SR_ZP, PERC, SUMMA, 
	PAYER = CASE WHEN  PAYER = 1 THEN 'Работодатель' else 'ФСС' end,
	CODE_KBK = KBK.CODE, ITOGO_DNI = @ITOGO_DNI, ITOGO_CH = @ITOGO_CH
from SDOC_ADIS_TABLE1 T2  LEFT JOIN dbo.SAL_SFIN KBK ON T2.LINK_KBK = KBK.LINK
where link_up = @LINK_DOC 

--ВЫВОД РАСШИФРОВКИ БАЗОВОЙ СУММЫ
DECLARE 
 @RefPay INT,
 @linkEmpl INT,
 @dDate1 DATETIME,
 @dDate2 DATETIME

SELECT 
	@RefPay = REF_PAY,
	@linkEmpl = REF_EMPL,
	@dDate1 = DATE_BEGIN,
	@dDate2 = DATEADD(MONTH,INSTRUCT*12,DATE_BEGIN) - 1
FROM 
	dbo.DOCUMENTS_ADD_ARCHE 
WHERE 
	LINK = @LINK_DOC

CREATE TABLE #BASE_SUM 
(
	CODE_PAYS VARCHAR(10), 
	NAME_PAYS VARCHAR(60),
	LINK_PAYS INT,
	LINK INT,
	SUMMA NUMERIC(18,2),
	[NAME_VKR] VARCHAR(30),
	MON TINYINT, 
	[YEAR] INT,  
	MON1 TINYINT, 
	YEAR1 INT
)

INSERT INTO #BASE_SUM (CODE_PAYS,NAME_PAYS,LINK_PAYS,LINK,SUMMA,NAME_VKR,MON,[YEAR],MON1,YEAR1)
EXECUTE [dbo].SALARY_BASE_SUM_PAY_EMPL @linkEmpl,@RefPay,@dDate1,@dDate2

IF EXISTS (SELECT * FROM #BASE_SUM)
	SELECT * FROM #BASE_SUM
ELSE
	SELECT CODE_PAYS = '',NAME_PAYS = '',LINK_PAYS = NULL,LINK = NULL,SUMMA = NULL,NAME_VKR = '',MON = NULL,[YEAR] = NULL,MON1 = NULL,YEAR1 = NULL




GO


GRANT EXECUTE ON dbo.[SA_REP_ARCHE] 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),
		  @HOURS2 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
SET @HOURS2 = (SELECT MAX(HOURS) FROM #TmpDays) 
SET @HOURS2 = ISNULL(@HOURS2-1,0)

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 (CASE WHEN (HOURS-1) >= 0 THEN (HOURS-1) ELSE @HOURS2 END) > 0
							THEN (CASE WHEN (HOURS-1) >= 0 THEN (HOURS-1) ELSE @HOURS2 END)
							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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	© Кейсистемс (Keysystems), 2006
	Для подсвечивания итоговых ячеек
*/


CREATE PROCEDURE dbo.RO_TOTAL_CELLS
	@iLinkTable int,
	@iLSF	int = NULL,
	@NameCol varchar(8) = 'COL',
	@Mode	tinyint = 0, -- режим: 0 - цвет, 1 - readonly, 2 - цвет и реадонли
	@Code	tinyint = 0,  -- выводить ли поле Code и OrderRow, 0 - не выводить, 1 - выводить
    @cTmpName Varchar(100)='', --требуется для подсчета подитогов 428 формы,
    @tmp_table varchar(200)='', --данные во временную табличку
    @bDeleteEmptyRows BIT = NULL,  --  NULL - данные выбираются не для печати, 1 - удаление пустых строк (поле DEL = 1), 0 - не удалять.
	@web int=0 -- 1 вызов с веба или excel-клиента
as


declare @cStr varchar(8000), 
	@cStr1 varchar(8000),
	@cStr2 varchar(8000),
	@cStr3 varchar(8000),
    @cStr3_1 varchar(8000),
	@cStr4 varchar(8000),
	@cStr5 varchar(8000),
	@cStr0 varchar(8000),
	@ctmp varchar(8000),
	@LinkForm int,
	@LinkCol int,
	@Orders tinyint,
	@ValType tinyint,
	@ColType tinyint,
	@IsEdited tinyint,
	@RGB_zapret varchar(10),
	@RGB_itog varchar(10),
	@RGB_zapret_simple varchar(10),
	@RGB_zapret_itog varchar(10),
	@RGB_name varchar(10),
	@RGB_name_dinamic varchar(10),
	@RGB_simple varchar(10),
    @orders_col int,
	@is_dinamic INT,
   @DictWhere VARCHAR(1000)

IF IS_MEMBER('Свод-КС - ограниченый доступ к организациям') = 1 AND ISNULL((SELECT Val_INT FROM report_options WHERE [Razdel] = 'COMMON' AND CODE = 'ACCESS_WEB'),0) = 0
BEGIN
   SET @web = 1
END       
 
CREATE TABLE #tmp_col (link_col INT)
INSERT #tmp_col (link_col)
select link_col from report_saved_forms_permissions (NOLOCK) where lsf=@iLSF

IF @cTmpName=''
	set @cTmpName='#i_report_dinamic_rows'

set @RGB_zapret = case @Mode when 0 then '14474460' when 2 then '-14474460' else '1' end
set @RGB_itog = case @Mode when 0 then '14483420' when 2 then '14483420' else '0' end
set @RGB_name = case @Mode when 0 then '15790320'  when 2 then '-15790320' else '1' end
set @RGB_simple = case @Mode when 0 then '16777215' when 2 then '16777215' else '0' end
set @RGB_zapret_itog = case @Mode when 0 then '9086343' when 2 then '-9086343'/*'-12189625'*/ else '1' end
set @RGB_zapret_simple = case @Mode when 0 then '12632256' when 2 then '-12632256'/*'-11447982'*/ else '1' end
	
select @is_dinamic=isnull(is_dinamic,0),@LinkForm = Link_Form, @ValType = Val_Type from report_tables where Link_Table = @iLinkTable


if @LinkForm is NULL
	return -1
/*
SELECT *
INTO report_coloumns
FROM dbo.REPORT_COLOUMNS
WHERE link_table = @iLinkTable
*/

DECLARE SEL_CURSOR  CURSOR STATIC LOCAL
	FOR SELECT DISTINCT LINK_Col, Col_Type, IsEdited,orders
	FROM report_coloumns WHERE LINK_Table=@iLinkTable order by orders 

declare @link int,@condrows varchar(2500),@ExecStr nvarchar(4000),@link_col int,@condCols varchar(250),@code_row varchar(100),@link_row int
create table #cols (link_col int)


declare @cDinamic varchar(8000),@cSuffix_table varchar(100)
set @cDinamic=''

declare @sort_kod int
IF exists(select * from report_coloumns where link_col=(select link_code_col from report_tables where link_table=@iLinkTable) and property&8>0)
	set	@sort_kod=1
else
	set	@sort_kod=0
declare @region varchar(250)
--сформируем список доступных правил
create table #tmp_rules_list (LINK_RULE int,REGION varchar(100),orderRule int, Link_Col int, Link_Row int, Code_Row varchar(100), Filter varchar(1000), Val_Type tinyint, IsDoschet tinyint, rows varchar(1000), cols varchar(1000))
Create index #IX_tmp_rules_list on #tmp_rules_list (link_rule,region)
exec X_GET_OPTION 'OBJ_FTP_REGION',0,@cStr output 	
set @region=rtrim(isnull(@cstr,''))
	insert #tmp_rules_list
	SELECT R.[LINK_RULE],
          isnull([REGION],''),OrderRule, Link_Col, Link_Row, Code_Row, Filter, Val_Type, IsDoschet, rows, ',' + REPLACE(REPLACE(cols, ' ',''), '-', '') + ','
	FROM dbo.[REPORT_CONTROL_RULES] [R] (NOLOCK) join dbo.report_control_rows Ro (NOLOCK) on R.Link_Rule = Ro.Link_Rule and Ro.OrderRow = 1 and Ro.Link_Table = @iLinkTable
	 where R.link_form=@LinkForm and IsOutside = 0 and (isnull(R.region,'')=@region or isnull(R.region,'')='')-- and IsDoschet &1 = 1
	IF @region<>''
	begin
		delete #tmp_rules_list 
      from #tmp_rules_list A JOIN dbo.[REPORT_CONTROL_RULES] rcr ON rcr.[LINK_RULE] = A.[LINK_RULE] 
      where A.region='' and 
			exists(select * from report_control_rows C
                              JOIN dbo.[REPORT_CONTROL_RULES] rcr2 ON rcr2.[Link_Rule] = C.[Link_Rule] 
                where C.link_rule in (select link_rule from #tmp_rules_list where region<>'')
                     AND rcr.[sign_sr] = rcr2.[sign_sr]
			            and C.orderRow=1 and isnull(C.link_row,0)=isnull(A.link_row,0) and isnull(C.code_row,'')=isnull(A.code_row,'') and isnull(C.link_col,0)=isnull(A.link_col,0) and isnull(C.link_table,0)=@iLinkTable)

--		delete #tmp_rules_list 
--		WHERE Link_Rule IN (SELECT Ru1.Link_Rule FROM report_control_rules Ru1 JOIN #tmp_rules_list T1 ON Ru1.Link_Rule = T1.Link_Rule 
--						WHERE T1.region='' AND EXISTS(SELECT TOP 1 * FROM report_control_rules Ru2 JOIN #tmp_rules_list T2 ON Ru2.Link_Rule = T2.Link_Rule 
--								WHERE T2.region <> '' AND Ru1.Str_Rule = Ru2.Str_Rule))

	end

delete #tmp_rules_list where IsDoschet & 1 = 0

if @ValType = 0
begin --------------------- таблица статическая ----------------------------------

IF @iLSF>0  and @is_dinamic>0
	begin
		IF exists(select * from report_saved_forms where link_saved_form=@iLSF and is_arhiv=1)
			set @cSuffix_table='_ARH'
		else
			set @cSuffix_table=''
		set @cDinamic=
		' and (exists(select link_row from report_string'+@cSuffix_table+' RS where RS.link_saved_form='+ltrim(str(@iLSF))+' and RS.link_row=RR.link_row)
		or exists(select link_row from report_summa'+@cSuffix_table+' RS where RS.link_saved_form='+ltrim(str(@iLSF))+' and RS.link_row=RR.link_row))'
	end

create table #Stat_filters(link int identity (1,1),filters varchar(2500),link_col int,cols varchar(250),link_row int)
create table #stat_code_row (link_row int,link_col int)

insert #Stat_filters
select CASE WHEN R2.Val_Type=0 AND (R2.LINK_ROW IS NOT NULL OR R2.CODE_ROW <>'') THEN '' ELSE R1.rows END,R2.link_col,R1.cols,R2.link_row
from report_control_rules R1  (nolock) inner join report_control_rows R2 (nolock) on R1.Link_Rule = R2.Link_Rule and R2.OrderRow = 1 and R2.Link_Table = (@iLinkTable)   and IsDoschet&1= 1 and isOutSide=0 and R2.val_type=0 and (R1.rows<>'' or R1.cols<>'' )
	inner join #tmp_rules_list T on T.Link_Rule = R1.Link_Rule
--WHERE R2.Val_Type <> 0  

insert #Stat_filters
select case when R1.rows<>'' then ' (' + CASE WHEN rtrim(R1.rows) LIKE '%#t_summa%' THEN '1=1' ELSE  rtrim(R1.rows) END +') and ' else '' end + R2.filter,R2.link_col,R1.cols,R2.link_row
from report_control_rules R1  (nolock) inner join report_control_rows R2 (nolock) on R1.Link_Rule = R2.Link_Rule and R2.OrderRow = 1 and R2.Link_Table = (@iLinkTable)   and IsDoschet&1 = 1 and isOutSide=0 and R2.val_type=4 and (R2.filter<>'')
	inner join #tmp_rules_list T on T.Link_Rule = R1.Link_Rule

if exists(select * from  #Stat_filters)
    select * into #i_report_rows from i_report_rows A (nolock) where   A.link_table = @iLinkTable

while exists(select top 1 * from  #stat_filters)
begin
  select top 1 @link=link,@CondRows = [filters],@link_col = [link_col],@condCols=[cols],@link_row=link_row from #stat_filters


  delete from #cols
    insert #cols
      select A.Link_Col
      from 
      (select RC.Link_Col, RC.orders
      from report_coloumns RC (nolock)where  RC.Link_Table =@iLinkTable  and RC.Col_Type = 0) A
       where  @link_col = A.link_col OR (@link_col IS NULL AND @condCols = '') or (@condCols <> '' and CHARINDEX(',' + LTRIM(STR(A.Orders)) + ',', ',' + RTRIM(@condCols) + ',') > 0) 
       
       
     IF @CondRows=''
	set @CondRows='1=0'
      set @ExecStr = 'insert #stat_code_row
     select  A.link_row, B.link_col'+
    ' from  #i_report_rows A left join #cols B on B.link_col>0 '+
    ' where A.code<>'''' and  ('+
    REPLACE(CASE WHEN @CondRows LIKE '%#t_summa%' THEN '1=1' ELSE @CondRows END, 'COL(', '(select case when col_type = 0 then STR((select  top 1 summa from report_summa S where Link_Saved_Form = ' + LTRIM(STR(@iLSF))+ ' and S.Link_col = RC.link_col and S.Link_Row = A.Link_Row), 20,4) else (select formula from report_formula F where F.link_col = RC.link_col and F.link_row = A.Link_Row) end from report_coloumns RC where link_table = ' + STR(@iLinkTable) + ' and orders =')
--'dbo.RO_COL_Static(' + LTRIM(STR(@iLinkTable)) + ', A.Link_Row,')
+
    ' or A.link_row='+STR(ISNULL(@link_row,0))+')' 


      execute(@ExecStr)
      delete #stat_filters where link=@link
END


set @cStr1 = '
create table #tmp 
(link_col int,
 link_row int)

Create index #ix_tmp on #tmp (link_row,link_col)

--обработка фильтра правила 
insert #tmp (Link_Col, link_Row)
select  Link_Col, link_Row from #stat_code_row

insert into #tmp (link_col,link_row)
select distinct R2.Link_Col, R2.Link_Row
from report_control_rules R1  (nolock) inner join report_control_rows R2 (nolock) on R1.Link_Rule = R2.Link_Rule and R2.OrderRow = 1 and R2.Link_Table = ' + LTRIM(STR(@iLinkTable)) + ' and IsDoschet&1 = 1 and isOutSide=0 and R2.val_type=0 and (R1.rows='''' and R1.cols='''')
	inner join #tmp_rules_list T on T.Link_Rule = R1.Link_Rule

if exists(select * from #tmp where Link_Col is NULL)
begin
	insert into #tmp (link_col,link_row)
		select RC.Link_Col, T.Link_Row
		from report_coloumns RC left join #tmp T on T.Link_Col is NULL
		where Link_table = ' + LTRIM(STR(@iLinkTable)) + ' and RC.IsEdited=1 and RC.Col_Type=0
	delete from #tmp where Link_Col is null
end
if exists(select * from #tmp where Link_Row is NULL)
begin
	insert into #tmp (link_col,link_row)
		select T.Link_Col, RR.Link_Row
		from report_rows RR (nolock) left join #tmp T on T.Link_Row is NULL 
		where Link_table = ' + LTRIM(STR(@iLinkTable)) + '
	delete #tmp where Link_Row is null
end'

set @cStr = '
select ' + case @Code when 1 then 'convert(varchar(100), isnull(Code,'''')) as Cod, Orders as OrderRow, ' else '' end
set @cStr2 = ''
set @cStr3 = ''
set @cStr3_1 = ''
set @cStr4 = ''
set @cStr5 = ''

--set @Orders = 1 -- считается не по порядковому номеру столбца, т.к. он может быть не по порядку
OPEN SEL_CURSOR
FETCH NEXT FROM SEL_CURSOR INTO @LinkCol, @ColType, @IsEdited,@orders_col
set @Orders =@orders_col
while @@fetch_status = 0
begin

	IF @cDinamic<>'' and @IsEdited=0 
		set @RGB_name = case @Mode when 0 then '15790320'  when 2 then '16777215' else '1' end
	else
		set @RGB_name = case @Mode when 0 then '15790320'  when 2 then '-15790320' else '1' end


	if @Orders < 15 
	begin
	if @IsEdited = 1 and dbo.RO_AccessColByLink(@LinkCol) > 0 
            and (not exists(select * from #tmp_col where link_col=@LinkCol) or @web<>1 )
	begin
	set @cStr = @cStr + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row=RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row=RR.Link_Row and Link_Col=' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_itog + ' else ' + @RGB_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
	end
	else
		if @IsEdited = 0 -- наименования, код строки
		begin
			set @cStr = @cStr + '
' + @RGB_Name + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
		end
		else begin -- нет доступа к колонке
--			set @cStr = @cStr + '
--' + @RGB_Zapret + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
	set @cStr = @cStr + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row=RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row=RR.Link_Row and Link_Col=' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_zapret_itog + ' else ' + @RGB_zapret_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '

		end
	end
	else begin
	if @Orders < 27
	begin
		if @IsEdited = 1 and dbo.RO_AccessColByLink(@LinkCol) > 0
            and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
		begin
		set @cStr2 = @cStr2 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row=RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row=RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row=RR.Link_Row and Link_Col=' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_itog + ' else ' + @RGB_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
		end
		else begin
			if @IsEdited = 0 -- наименования, код строки
			begin
				set @cStr2 = @cStr2 + '
' + @RGB_Name + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			end
			else begin -- нет доступа к колонке
--				set @cStr2 = @cStr2 + '
--' + @RGB_Zapret + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
		set @cStr2 = @cStr2 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row=RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row=RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row=RR.Link_Row and Link_Col=' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_zapret_itog + ' else ' + @RGB_zapret_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '

			end
		end
	end
	else begin
		if @Orders < 38
		begin
			if @IsEdited = 1 and dbo.RO_AccessColByLink(@LinkCol) > 0
               and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
			begin
			set @cStr3 = @cStr3 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF  (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row = RR.Link_Row and Link_Col = ' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_itog + ' else ' + @RGB_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			end
			else begin
				if @IsEdited = 0 -- наименования, код строки
				begin
					set @cStr3 = @cStr3 + '
' + @RGB_Name + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
				end
				else begin -- нет доступа к колонке
--					set @cStr3 = @cStr3 + '
--' + @RGB_Zapret + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			set @cStr3 = @cStr3 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF  (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row = RR.Link_Row and Link_Col = ' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_zapret_itog + ' else ' + @RGB_zapret_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '

				end
			end
		end
	else begin
		if @Orders < 48
		begin
			if @IsEdited = 1 and dbo.RO_AccessColByLink(@LinkCol) > 0
                and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
			begin
			set @cStr3_1 = @cStr3_1 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF  (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row = RR.Link_Row and Link_Col = ' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_itog + ' else ' + @RGB_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			end
			else begin
				if @IsEdited = 0 -- наименования, код строки
				begin
					set @cStr3_1 = @cStr3_1 + '
' + @RGB_Name + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
				end
				else begin -- нет доступа к колонке
--					set @cStr3_1 = @cStr3_1 + '
--' + @RGB_Zapret + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			set @cStr3_1 = @cStr3_1 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF  (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row = RR.Link_Row and Link_Col = ' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_zapret_itog + ' else ' + @RGB_zapret_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '

				end
			end
		end
		else begin
			if @IsEdited = 1 and dbo.RO_AccessColByLink(@LinkCol) > 0 
               and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
			begin
			set @cStr4 = @cStr4 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row = RR.Link_Row and Link_Col = ' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_itog + ' else ' + @RGB_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			end
			else begin
				if @IsEdited = 0 -- наименования, код строки
				begin
					set @cStr4 = @cStr4 + '
' + @RGB_Name + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
				end
				else begin -- нет доступа к колонке
--					set @cStr4 = @cStr4 + '
--' + @RGB_Zapret + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			set @cStr4 = @cStr4 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row = RR.Link_Row and Link_Col = ' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_zapret_itog + ' else ' + @RGB_zapret_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '

				end
			end
		end
	end
	END
   END
	FETCH NEXT FROM SEL_CURSOR INTO @LinkCol, @ColType, @IsEdited,@orders_col
	set @Orders =@orders_col
--	set @Orders = @Orders + 1
end
if @cStr2 = ''
begin
	set @cStr = LEFT(RTRIM(@cStr),LEN(RTRIM(@cStr)) - 1)
--	set @cStr = @cStr + '
--	'+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' from i_report_rows RR (nolock) where Link_Table=' + LTRIM(STR(@iLinkTable)) + @cDinamic+' order by RR.orders'
end
else begin
	if @cStr3 = ''
	begin
		set @cStr2 = LEFT(RTRIM(@cStr2),LEN(RTRIM(@cStr2)) - 1)
--		set @cStr2 = @cStr2 + '
--     '+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
 --order by RR.orders'
	end
	else begin
	   if @cStr3_1 = ''
	   begin
		   set @cStr3 = LEFT(RTRIM(@cStr3),LEN(RTRIM(@cStr3)) - 1)
   --		set @cStr2 = @cStr2 + '
   --     '+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
    --order by RR.orders'
	   end
	   else begin
		   if @cStr4 = ''
		   begin
			   set @cStr3_1 = LEFT(RTRIM(@cStr3_1),LEN(RTRIM(@cStr3_1)) - 1)
   --			set @cStr3 = @cStr3 + '
   --	'+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
   --	 from i_report_rows RR where Link_Table=' + LTRIM(STR(@iLinkTable)) + ' order by RR.orders'
		   end
		   else begin
			   set @cStr4 = LEFT(RTRIM(@cStr4),LEN(RTRIM(@cStr4)) - 1)
   --			set @cStr4 = @cStr4 + '
   --	'+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
   --	 from i_report_rows RR where Link_Table=' + LTRIM(STR(@iLinkTable)) + ' order by RR.orders'
         end
		end
	end
end

	set @cStr5 = @cStr5 + '
	'+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
	 from i_report_rows RR where Link_Table=' + LTRIM(STR(@iLinkTable)) +@cDinamic+ ' order by RR.'+case when @sort_kod=1 then 'CODE' else 'orders' end




execute(@cStr1 + @cStr + @cStr2 + @cStr3 + @cStr3_1 + @cStr4+@cStr5  /* +' drop table #tmp'*/)

end------------------------------------------------------------------------
else begin ------------------------- таблица динамическая -----------------
if @iLSF is NULL
	return -2
----------------------------------------------------------------------------
-- новая подкраска:
	declare @IsArchive tinyint, @WithCol tinyint
	create table #Cells (Link_Col int, Code_Row varchar(100))
	create table #t_Exec (txt varchar(8000))
	create table #Coloumns (Link_Col int, orders tinyint, Col_Type tinyint)

	insert #Coloumns (Link_Col, orders, Col_Type)
	select Link_Col, orders, Col_Type
	from dbo.report_coloumns 
	where Link_Table = @iLinkTable --and Col_Type = 0

	if exists(select top 1 * from #tmp_rules_list where rows like '%COLS(%' or filter like '%COLS(%' or rows like '%COL(%' or filter like '%COL(%' or rows like '%report_dinamic%' or filter like '%report_dinamic%')
		set @WithCol = 1
	else
		set @WithCol = 0
	
	--create table #tmp_rules_list1 (LINK_RULE int,REGION varchar(100),orderRule int, Link_Col int, Link_Row int, Code_Row varchar(100), Filter varchar(1000), Val_Type tinyint, IsDoschet tinyint, rows varchar(1000), cols varchar(1000))

--	select @IsArchive = Is_Arhiv from dbo.report_saved_forms where Link_Saved_Form =@iLSF 

		create table #i_report_dinamic_rows(Link_SF int,CODE_ROW varchar(100),link_table INT, link_col INT, float_val FLOAT, str_val VARCHAR(8000), for_rash char(3), for_doh char(10))

	Create index #IX_report_dinamics on #i_report_dinamic_rows (link_col,code_row)
	Create index #IX_report_dinamics_rash on #i_report_dinamic_rows (link_sf, link_col,for_rash)
	Create index #IX_report_dinamics_doh on #i_report_dinamic_rows (link_sf, link_col,for_doh)

--	while exists(select top 1 * from #Coloumns)
--	begin
--		select top 1 @link = link_col from 	#Coloumns	
--		set @ExecStr='INSERT #i_report_dinamic_rows (Link_SF,CODE_ROW,link_table,link_col,float_val, str_val, for_rash) SELECT 	' + str(@iLSF) + ', 	RD.Code_Row, 	' + LTRIM(STR(@iLinkTable)) + ', RD.Link_Col, RD.Float_Val, RD.Str_Val, RIGHT(RTRIM(RD.Code_Row),3)
--			FROM '+CASE WHEN @cTmpName = '#i_report_dinamic_rows' THEN case when  @IsArchive = 0 then 'dbo.report_dinamics' else 'dbo.report_dinamics_arh' end ELSE @cTmpName END +' RD where  RD.link_col = ' + STR(@link) + ' and RD.Link_SF ='+str(@iLSF)
--		execute(@ExecStr)
--		delete #Coloumns where link_col = @link
--	end

	if @cTmpName = '#i_report_dinamic_rows'
	begin
		if @WithCol = 1
		begin
			while exists(select top 1 * from #Coloumns)
			begin
				select top 1 @link = link_col from 	#Coloumns	
				INSERT #i_report_dinamic_rows (Link_SF,CODE_ROW,link_table,link_col,float_val, str_val, for_rash, for_doh) SELECT 	@iLSF,	RD.Code_Row, 	@iLinkTable, RD.Link_Col, RD.Float_Val, RD.Str_Val, RIGHT(RTRIM(RD.Code_Row),3), left(RD.code_row,10)
					FROM dbo.report_dinamics_all RD where  RD.link_col = @link and RD.Link_SF =@iLSF
				delete #Coloumns where link_col = @link
			end
		end
		else begin
			INSERT #i_report_dinamic_rows (Link_SF,CODE_ROW,link_table,link_col,float_val, str_val, for_rash, for_doh) 
			SELECT 	@iLSF, 	RD.Code_Row, 	@iLinkTable, 0, 0, '', RIGHT(RTRIM(RD.Code_Row),3), left(RD.code_row,10)
			FROM dbo.report_dinamics_all  RD join dbo.report_coloumns RC on RD.link_col = RC.Link_Col and RD.Link_SF = @iLSF and RC.link_table = @iLinkTable
			group by RD.Code_Row
		end
	end
	else begin
		set @ExecStr='INSERT #i_report_dinamic_rows (Link_SF,CODE_ROW,link_table,link_col,float_val, str_val, for_rash, for_doh) SELECT 	' + str(@iLSF) + ', 	RD.Code_Row, 	RC.link_table, RD.Link_Col, RD.Float_Val, RD.Str_Val, RIGHT(RTRIM(RD.Code_Row),3), left(RD.Code_Row,10)
			FROM '+ @cTmpName +' RD left join report_coloumns RC
			on RD.link_col = RC.Link_Col and RC.link_table = '+str(@iLinkTable)
		execute(@ExecStr)
	end

	-- когда указаны строки:
	insert #Cells (Link_Col, Code_Row)
	select RC.Link_Col, Code_Row
	from #tmp_rules_list T left join dbo.report_coloumns RC on RC.Link_Table = @iLinkTable and RC.Col_Type = 0 and (RC.Link_Col = T.Link_Col or T.Link_Col is NULL)
	where Val_Type = 3 and  isnull(Code_Row, '') <> '' and (T.cols = ',,' or CHARINDEX(',' + LTRIM(RTRIM(STR(RC.orders))) + ',', T.cols) > 0)

	delete #tmp_rules_list where Val_Type = 3 and isnull(Code_Row, '') <> ''
	-- для всех строк
	insert #Cells (Link_Col, Code_Row)
	select RC.Link_Col, D.Code_Row
	from #tmp_rules_list T left join dbo.report_coloumns RC on RC.Link_Table = @iLinkTable and RC.Col_Type = 0 and (RC.Link_Col = T.Link_Col or T.Link_Col is NULL)
			left join #i_report_dinamic_rows D on 1 = 1
	where Val_Type = 3 and T.rows = '' and  isnull(T.Code_Row, '') = ''  and (T.cols = ',,' or CHARINDEX(',' + LTRIM(RTRIM(STR(RC.orders))) + ',', T.cols) > 0)

	delete #tmp_rules_list where Val_Type = 3 and rows = ''

	-- не указаны строки:
		update #tmp_rules_list
		set filter = REPLACE(REPLACE(REPLACE(filter, 'right(rtrim(code),3)', 'A.for_rash'), 'left(code,10)', 'A.for_doh'), 'left(RD1.Code_row,10)', 'RD1.for_doh')
		update #tmp_rules_list
		set filter = REPLACE(filter, 'right(rtrim(RD1.code_row),3)', 'RD1.for_rash')

		while exists(select top 1 * from  #tmp_rules_list where Val_Type = 4 or rows <> '')
		begin
--		insert #t_Exec (txt)
		  select @link = Link_Rule, @ExecStr = --'insert #tmp_rules_list1 (LINK_RULE,REGION,orderRule, Link_Col, Link_Row, Code_Row, Filter, Val_Type, IsDoschet, rows, cols) ' + 
			'insert #Cells (Link_Col, Code_Row)' +
		 --'select ' + LTRIM(RTRIM(STR(Link_Rule))) + ', '''', 0, ' + isnull(STR(Link_Col), 'NULL') + ' , NULL, A.Code_Row, '''', 3, 1, '''', '''+ cols + ''' '  +
		'select B.Link_Col, A.Code_Row from  #i_report_dinamic_rows A left join dbo.report_coloumns B on B.Link_Table = ' + LTRIM(STR(@iLinkTable)) + ' and B.col_type = 0 '+ case when Link_Col is NOT NULL then ' and B.Link_Col = ' + LTRIM(STR(Link_Col)) else '' end +
		' where ' + case when cols <> ',,' and Link_Col is NULL then 'CHARINDEX('','' + LTRIM(RTRIM(STR(B.orders))) + '','', ''' + cols +  ''') > 0 and ' else '' end +	REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE((case when [filter] <> '' then '(' + RTRIM(filter) + ')' else '(1=1)' end + case when [rows] <> '' then ' and (' + RTRIM([rows]) + ')' else '' end ),'report_dinamics_all','#i_report_dinamic_rows'), 'report_dinamics', '#i_report_dinamic_rows'), 'CODE', 'A.Code_Row'),'.A.Code_Row', '.CODE'), 'COL(','(select top 1 case when Col_Type = 0 then float_val else str_val end from '+@cTmpName+'  RF (nolock) inner join report_coloumns RC (nolock) on RF.Link_sf = ' + LTRIM(STR(@iLSF))+' and RF.Link_Col = RC.Link_Col   and RF.Code_Row = A.Code_Row and RC.Link_Table =' + LTRIM(STR(@iLinkTable))+' and RC.orders ='), '##i_report_dinamic_rows', '#i_report_dinamic_rows'), 'COLS(','(select top 1 str_val from '+@cTmpName+'  RF (nolock) inner join report_coloumns RC (nolock) on RF.Link_sf = ' + LTRIM(STR(@iLSF))+' and RF.Link_Col = RC.Link_Col   and RF.Code_Row = A.Code_Row and RC.Link_Table =' + LTRIM(STR(@iLinkTable))+' and RC.orders =')
		from #tmp_rules_list T where Val_Type = 4 or rows <> ''
		

  	-- атрибуты в фильтрах
   SELECT @ExecStr = REPLACE(@ExecStr, '#' + rtrim(code_atr) + '#', '''' + str_val + '''')
   FROM dbo.[REPORT_ATRIBUT_VALUES] rav
   WHERE rav.[link_saved_form] = @ilsf
   
   SELECT  @ExecStr = REPLACE(@ExecStr, '#' + rtrim(SO1.code) + '#', '''' + isnull(OV.[VALUE],'') + '''')
   FROM dbo.s_objects SO
         JOIN dbo.s_objects SO1 ON SO.[LINK] = SO1.[LINK_SELF]
         JOIN dbo.s_property P ON P.Code = 'DEFAULT_VALUE'
         JOIN dbo.[OBJECT_VALUES] ov ON ov.[OBJECT] = SO1.[LINK] AND ov.[PROPERTY] = P.[LINK] 
   WHERE SO.Code = 'REPORTS_ATR'
              

--			exec ssp_execresultset 'select txt from #t_Exec'--, @varKSDebug = 1
		print @ExecStr
      PRINT @link
			exec sp_executesql @ExecStr, N'@link_rule int', @link_rule = @link
--
			delete #tmp_rules_list where link_rule=@link
		end

	-- по ДЕРЕВУ КБК досчет
   CREATE table #t_TreeKBK_cols (Link_Table int, Cols varchar(100))

	insert #t_TreeKBK_cols (Link_Table, Cols)
	select Link_Table, replace(isnull(dbo.rn_get_formula_code_row_f(Link_Table,'KBK='),''),'-', '')
	from report_tables rt
   WHERE link_table = @iLinkTable
         
   UPDATE #t_TreeKBK_cols
   SET cols = ''
   WHERE cols LIKE '%(%' AND (cols NOT LIKE '%' + RTRIM(@region) + '%' OR @region = '') 
   
	declare @Dict varchar(100)
	select @Dict = Dictionary, @DictWhere = isnull(RC.[Dictionary_Where],'')
	  from report_tables RT join report_coloumns RC on RT.Link_Code_Col = RC.Link_Col where Doschet_Tree = 1 and isnull(Dictionary,'') <> '' and RT.Link_Table = @iLinkTable
	if isnull(@Dict, '') <> ''
	begin
		if COLUMNPROPERTY(object_id('[dbo].' + LTRIM(RTRIM(@Dict))), 'Link_Self', 'AllowsNull') is NOT NULL
		BEGIN
            SELECT @DictWhere = REPLACE(REPLACE(REPLACE(@DictWhere, '%link_org%', LTRIM(STR(rsf.[Link_Organization]))), '%link_budg%', LTRIM(STR(ISNULL(rsf.[Link_Type_Svod], 0)))), '%date%', '''' + CONVERT(VARCHAR(10), rsf.[Begin_Date], 112) + '''')
            FROM dbo.[REPORT_SAVED_FORMS] rsf
            WHERE rsf.[Link_Saved_Form] = @iLSF
            
            IF ISNULL(@iLSF, 0) = 0
            BEGIN
               IF (SELECT code FROM dbo.[REPORT_FORMS] rf WHERE rf.[Link_Form] = @LinkForm) LIKE '%G%'
                  SET @DictWhere = REPLACE(REPLACE(REPLACE(@DictWhere, '%link_org%', '0'), '%link_budg%', '0'), '%date%', '''' + CONVERT(VARCHAR(10), DATEADD(MONTH,-3, GETDATE()), 112) + '''')
               ELSE                   
                  SET @DictWhere = REPLACE(REPLACE(REPLACE(@DictWhere, '%link_org%', '0'), '%link_budg%', '0'), '%date%', '''' + CONVERT(VARCHAR(10), DATEADD(MONTH,-1, GETDATE()+10), 112) + '''')
            END    
         
			  set @ExecStr = 'insert #Cells
				select  B.Link_Col, T.Code
				from dbo.' + RTRIM(@Dict) + ' T join dbo.report_coloumns B on B.Link_Table = @iLinkTable and B.Col_Type = 0
               join #t_TreeKBK_cols tc on tc.link_table = B.link_table AND (CHARINDEX('','' + LTRIM(RTRIM(STR(B.orders))) + '','', '','' + rtrim(tc.cols) + '','') > 0 OR cols = '''')
				where  exists(select * from dbo.' + LTRIM(@Dict) + ' T1 where T1.Link_Self = T.Link ' + CASE WHEN @DictWhere = '' THEN  '' ELSE ' and ' + @DictWhere END  + ' ) '
				--print @ExecStr
				exec sp_executesql @ExecStr, N'@iLinkTable int', @iLinkTable = @iLinkTable
		end
	end

--	insert #t_Exec (txt)
	select @cStr = case when @Code = 0 then 'select ' else 'select RD.Code_Row as Cod,0 as OrderRow,' end

OPEN SEL_CURSOR
FETCH NEXT FROM SEL_CURSOR INTO @LinkCol, @ColType, @IsEdited,@orders_col
--set @Orders = 1
set @Orders =@orders_col
while @@fetch_status = 0
begin
	if dbo.RO_AccessColByLink(@LinkCol) > 0 
         and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
	begin
		set @cStr = @cStr + @NameCol + LTRIM(STR(@Orders)) + '=min(case when T.Link_Col=' + LTRIM(STR(@LinkCol)) + ' then ' + @RGB_itog + ' else '+@RGB_simple+' end),
'
		end
		else begin -- нет доступа к колонке
--			set @cStr = @cStr + @NameCol + LTRIM(STR(@Orders)) + '=' + @RGB_zapret + ',
--'		
		set @cStr = @cStr + @NameCol + LTRIM(STR(@Orders)) + '=' + CASE WHEN @Mode = 2 THEN 'max' ELSE  'min' END + '(case when T.Link_Col=' + LTRIM(STR(@LinkCol)) + ' then ' + @RGB_zapret_itog + ' else '+@RGB_zapret_simple+' end),
'

      end
	FETCH NEXT FROM SEL_CURSOR INTO @LinkCol, @ColType, @IsEdited,@orders_col
	set @Orders =@orders_col
end
set @cStr = LEFT(@cStr, LEN(@cStr) - 3)

-----------------------------------------------------------
-- сортировка
   DECLARE @order_rule VARCHAR(8000), @order_rule_new VARCHAR(8000), @count_rule INT, @i INT, @order_rule_curr VARCHAR(8000)
	select @order_rule=rtrim(isnull(order_rule,'')) from report_tables where link_table = @iLINKTABLE
	set @order_rule_new=''
	--превратим @order_rule в условие
	IF @order_rule<>''
		begin
			set @order_rule_new=' case '
			set @count_rule=dbo.rn_getwordcount(@order_rule,char(13))
			set @i=1
			while @i<=@count_rule
				begin
					set @count_rule=dbo.rn_getwordcount(@order_rule,char(13))
					set @order_rule_curr=rtrim(dbo.rn_getwordnum(@order_rule,@i,char(13)))
					IF  @order_rule_curr<>''
						set @order_rule_new=@order_rule_new +' when '+ replace(UPPER(dbo.rn_getwordnum(@order_rule_curr,2,'#')),'CODE','RD.CODE_ROW')+' then '+REPLACE(dbo.rn_getwordnum(@order_rule_curr,1,'#'), 'RR.CODE_ROW', 'RD.CODE_ROW')
					set @i=@i+1
				end
			set @order_rule_new=@order_rule_new+' else 0 end ' 
		end
-----------------------------------------------------------

if @WithCol = 1
	set @cStr2 = case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
	from (SELECT DISTINCT code_row from #i_report_dinamic_rows) RD left join
		#Cells T on RD.Code_Row = T.Code_Row 
	group by RD.Code_Row
	order by ' + case when @order_rule_new <> '' then @order_rule_new + ',' ELSE '' end + ' RD.Code_Row'

else
	set @cStr2 = case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
	from   #i_report_dinamic_rows RD left join
		#Cells T on RD.Code_Row = T.Code_Row 
	group by RD.Code_Row
	order by ' + case when @order_rule_new <> '' then @order_rule_new + ',' ELSE '' end + ' RD.Code_Row'

--
CLOSE SEL_CURSOR
DEALLOCATE SEL_CURSOR

--set  @cStr = 'select count(*) '

--PRINT @cStr + @cStr2
execute (@cStr + @cStr2)	
return
------------------------------------------------------
--- старая подкраска:
--declare @name_table varchar(100)
--create table #filters_d (link int identity (1,1),filters varchar(2500),link_col int,cols varchar(250),code_row varchar(100))
--create table #code_row (code_row varchar(100),link_col int)
----create table #i_report_dinamic_rows(Link_SF int,CODE_ROW varchar(100),link_table INT, link_col INT, float_val FLOAT, str_val VARCHAR(8000), for_rash char(3))
--
--Create index #IX_report_dinamics on #i_report_dinamic_rows (link_sf, link_col,code_row)
--Create index #IX_report_dinamics_rash on #i_report_dinamic_rows (link_sf, link_col,for_rash)
--
--insert #filters_d
--select R1.rows,R2.link_col,R1.cols,R2.code_row
--from report_control_rules R1 (nolock) inner join report_control_rows R2 (nolock) on R1.Link_Rule = R2.Link_Rule and R2.OrderRow = 1 and R2.Link_Table = (@iLinkTable)   and IsDoschet&1 = 1 and isOutSide=0 and R2.val_type=3 and (R1.rows<>'' or R1.cols<>'' )
--where exists(select link_rule from #tmp_rules_list A where A.link_rule=R1.link_rule)
--
--
--insert #filters_d
--select R2.filter + case when R1.rows = '' then '' else ' and (' + R1.rows + ')' end ,R2.link_col,R1.cols,R2.code_row
--from report_control_rules R1 (nolock) inner join report_control_rows R2 (nolock) on R1.Link_Rule = R2.Link_Rule and R2.OrderRow = 1 and R2.Link_Table = (@iLinkTable)   and IsDoschet&1 = 1 and isOutSide=0 and R2.val_type=4 and (R2.filter<>'')--(R1.rows<>'' or R1.cols<>'' )
--where exists(select link_rule from #tmp_rules_list A where A.link_rule=R1.link_rule) 
--
----if exists(select * from  #filters_d)
----	begin
--		set @ExecStr='INSERT #i_report_dinamic_rows (Link_SF,CODE_ROW,link_table,link_col,float_val, str_val, for_rash) SELECT 	' + str(@iLSF) + ', 	RD.Code_Row, 	RC.link_table, RD.Link_Col, RD.Float_Val, RD.Str_Val, RIGHT(RTRIM(RD.Code_Row),3)
--			FROM '+CASE WHEN @cTmpName = '#i_report_dinamic_rows' THEN 'report_dinamics_all' ELSE @cTmpName END +' RD left join report_coloumns RC
--			on RD.link_col = RC.Link_Col
--			where  RD.Link_SF ='+str(@iLSF)+'  and RC.link_table = '+str(@iLinkTable)
--		execute(@ExecStr)
--
--set @name_table = case when @iLSF = 0 then 'report_dinamics_all' else '#i_report_dinamic_rows' end
----	end
--
----select * into ##i_report_dinamic_rows from #i_report_dinamic_rows
----
----  select A.Link_Col
----into ##cols
----  from 
----      (select RC.Link_Col, RC.orders
----      from report_coloumns RC (nolock)where  RC.Link_Table =@iLinkTable  and RC.Col_Type = 0) A
--
--if @iLSF > 0
--begin
--	update #filters_d
--	set filters = REPLACE(filters, 'right(rtrim(code),3)', 'A.for_rash')
--	update #filters_d
--	set filters = REPLACE(filters, 'right(rtrim(RD1.code_row),3)', 'RD1.for_rash')
--end
--
--
--while exists(select top 1 * from  #filters_d)
--begin
--
--  select top 1 @link=link,@CondRows = [filters],@link_col = [link_col],@condCols=[cols],@code_row=code_row from #filters_d
--
--delete from #cols
--insert #cols
--  select A.Link_Col
--  from 
--      (select RC.Link_Col, RC.orders
--      from report_coloumns RC (nolock)where  RC.Link_Table =@iLinkTable  and RC.Col_Type = 0) A
--       where  @link_col = A.link_col OR (@link_col IS NULL AND @condCols = '') or (@condCols <> '' and CHARINDEX(',' + LTRIM(STR(A.Orders)) + ',', ',' + RTRIM(@condCols) + ',') > 0) 
-- 
--  IF @CondRows=''
--	set @CondRows='1=0'
--  set @ExecStr = 'insert #code_row
-- select  A.Code_Row, B.link_col'+
--' from  #i_report_dinamic_rows A left join #cols B on B.link_col = A.Link_Col OR B.Link_Col > 0 '+
--' where A.code_row<>'''' and  ('+
--REPLACE(REPLACE(REPLACE(REPLACE(@CondRows,'report_dinamics_all',@name_table), 'CODE', 'A.Code_Row'),'.A.Code_Row', '.CODE'), 'COL(','(select top 1 case when Col_Type = 0 then float_val else str_val end from '+@cTmpName+'  RF (nolock) inner join report_coloumns RC (nolock) on RF.Link_sf = ' + LTRIM(STR(@iLSF))+' and RF.Link_Col = RC.Link_Col   and RF.Code_Row = A.Code_Row and RC.Link_Table =' + LTRIM(STR(@iLinkTable))+' and RC.orders =')+'
--or A.code_row='''+RTRIM(@code_row)+''')' 
--
--  exec sp_executesql @ExecStr
--
--  delete #filters_d where link=@link
--
--
--end
--
---- по ДЕРЕВУ КБК досчет
----declare @Dict varchar(100)
--select @Dict = Dictionary from report_tables RT join report_coloumns RC on RT.Link_Code_Col = RC.Link_Col where Doschet_Tree = 1 and isnull(Dictionary,'') <> '' and RT.Link_Table = @iLinkTable
--if isnull(@Dict, '') <> ''
--begin
--	if COLUMNPROPERTY(object_id('[dbo].' + LTRIM(RTRIM(@Dict))), 'Link_Self', 'AllowsNull') is NOT NULL
--	begin
--		delete #cols
--		insert #cols
--		select RC.Link_Col
--		from report_coloumns RC (nolock)where  RC.Link_Table =@iLinkTable  and RC.Col_Type = 0
--
--		  set @ExecStr = 'insert #code_row
--			select T.Code, B.Link_Col
--			from dbo.' + RTRIM(@Dict) + ' T , #cols B 
--			where  exists(select * from dbo.' + LTRIM(@Dict) + ' T1 where T1.Link_Self = T.Link) '
--			--print @ExecStr
--			execute(@ExecStr)
--	end
--end
--
--------------------
--set @cStr1 = 'declare @tmp table (Link_Col int, CodeRow varchar(100))
--insert @tmp (Link_Col, CodeRow)
--select distinct Link_Col, Code_Row as CodeRow
--from report_control_rules R1  inner join report_control_rows R2 (nolock) on R1.Link_Rule = R2.Link_Rule and R2.OrderRow = 1 and R2.Link_Table = ' + LTRIM(STR(@iLinkTable)) + ' and IsDoschet&1 = 1 and isOutSide=0 and R2.val_type=3 and (R1.rows='''' and	 R1.cols='''')
--where exists(select link_rule from #tmp_rules_list A where A.link_rule=R1.link_rule)
--
----обработка фильтра правила 
--insert @tmp (Link_Col, CodeRow)
--select  Link_Col, Code_Row from #code_row
--
--insert @tmp (Link_Col, CodeRow)
--select RC.Link_Col, Code_Row as CodeRow
--from report_dinamic_totals RDT left join report_coloumns RC (nolock) on RDT.Link_Table = RC.Link_Table and RC.orders = RDT.Order_Col
--where RDT.Link_Table = ' + LTRIM(STR(@iLinkTable)) + '
--
--if exists(select top 1 * from @tmp where Link_Col is NULL)
--begin
--	insert into @tmp
--		select RC.Link_Col, T.CodeRow
--		from report_coloumns RC left join @tmp T on T.Link_Col is NULL
--		where Link_table = ' + LTRIM(STR(@iLinkTable)) + ' and RC.IsEdited = 1 and RC.Col_Type = 0
--	delete @tmp where Link_Col is NULL
--end
--
--declare @Code table (Cod varchar(100) not null, LT int)
--insert @Code (Cod, LT) 
--
--select distinct Code_Row as Code, RC.Link_Table from '+ @cTmpName+' RD left join report_coloumns RC on RD.Link_Col = RC.Link_Col where RD.Link_SF =' + LTRIM(STR(@iLSF)) + ' and RC.Link_Table = ' + LTRIM(STR(@iLinkTable)) + 
--case when @bDeleteEmptyRows=1 then ' and abs(RD.float_val) > 0.001' else '' end +'
--if exists(select top 1 * from @tmp where LTRIM(ISNULL(CodeRow,'''')) = '''')
--begin
--	insert @tmp
--		select T.Link_Col, RR.Cod
--		from @Code RR left join @tmp T on LTRIM(ISNULL(T.CodeRow,'''')) = ''''
--	delete @tmp where LTRIM(ISNULL(CodeRow,'''')) = ''''
--end
--
--
--'
--
--set @cStr = case when @Code = 0 then '
--select ' else '
--select Cod,0 as OrderRow,
--'
--end
--
--set @cStr2 = ''
--set @cTmp = ''
--OPEN SEL_CURSOR
--FETCH NEXT FROM SEL_CURSOR INTO @LinkCol, @ColType, @IsEdited,@orders_col
----set @Orders = 1
--set @Orders =@orders_col
--while @@fetch_status = 0
--begin
--	if @Orders < 20
--	begin
----select * from #tmp_col where link_col=@LinkCol
--		if dbo.RO_AccessColByLink(@LinkCol) > 0 and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
--		begin
--			set @cStr = @cStr + @NameCol + LTRIM(STR(@Orders)) + '=min(case when T.Link_Col=' + LTRIM(STR(@LinkCol)) + ' then ' + @RGB_itog + ' else '+@RGB_simple+' end),
--'
--		end
--		else begin -- нет доступа к колонке
--			set @cStr = @cStr + @NameCol + LTRIM(STR(@Orders)) + '=' + @RGB_zapret + ',
--'		end
--	end
--	else begin
--		if dbo.RO_AccessColByLink(@LinkCol) > 0 and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
--		begin
--			set @cStr2 = @cStr2 + @NameCol + LTRIM(STR(@Orders)) + '=min(case when T.Link_Col=' + LTRIM(STR(@LinkCol)) + ' then ' + @RGB_itog + ' else '+@RGB_simple+' end),
--'
--		end
--		else begin -- нет доступа к колонке
--			set @cStr2 = @cStr2 + @NameCol + LTRIM(STR(@Orders)) + '=' + @RGB_zapret + ',
--'		end
--	end
--	FETCH NEXT FROM SEL_CURSOR INTO @LinkCol, @ColType, @IsEdited,@orders_col
----	set @Orders = @Orders + 1
--	set @Orders =@orders_col
--
--end
--if @cStr2 <> ''
--begin
--	set @cStr2 = LEFT(@cStr2, LEN(@cStr2) - 3)
--end
--else begin
--	set @cStr = LEFT(@cStr, LEN(@cStr) - 3)
--end
--
--set @cStr2 = @cStr2 + '
--'+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
--from  @Code RD
-- left merge join @tmp T on T.CodeRow = RD.Cod
--group by RD.Cod'
--
--CLOSE SEL_CURSOR
--DEALLOCATE SEL_CURSOR
--
--print @cStr1
--print @cStr
--print @cStr2
--print @cStr
--print @cStr2
----print   ') A
----group by Cod, OrderRow order by cod
----'
----print ' drop table #tmp'
--execute(@cStr1 + @cStr + @cStr2)

end 




GO
GRANT EXECUTE ON dbo.[RO_TOTAL_CELLS] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[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.[X_SAVE_DOCUMENTS_PAY2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[X_SAVE_DOCUMENTS_PAY2]

GO


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

CREATE     
PROCEDURE dbo.X_SAVE_DOCUMENTS_PAY2
	@varKSpLINK		int	OUTPUT,
	@varKSpINV_LINK int = null,
	@cBoNumber 		char(19) = '',
	@varKSpDOG_LINK INT = null,
	@iAvanse		tinyint = 0,
	@nNDSSumm		numeric(18,2) = 0,
	@nShort			bit = 0


AS
SET LOCK_TIMEOUT 30000
SET IMPLICIT_TRANSACTIONS ON
DECLARE 	@varKSstrVALUE	varchar(7000),
		@varKSEventText	varchar(254),
		@varKSERROR		int,
		@varKSRowCount	int,
		@varKStrancount	int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF exists (select * from FINANSE_PAYS where link = @varKSpLINK)
		UPDATE FINANSE_PAYS
			SET 
			Link_Invoice = @varKSpINV_LINK,
			BO_NUM	     = @cBoNumber,
			Link_Dogovor = @varKSpDOG_LINK,
			AVANSE		 = @iAvanse,
			SUMMA_NDS	 = @nNDSSumm,
			SHORT		 = @nShort
		WHERE Link = @varKSpLINK
	ELSE 
	BEGIN
		ROLLBACK
		RETURN 2
	END
	SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
	IF @varKSERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	IF @varKSRowCount = 0
	BEGIN
		ROLLBACK
		RETURN 2
	END

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0










GO


GRANT EXECUTE ON dbo.[X_SAVE_DOCUMENTS_PAY2] TO PUBLIC

GO



GO

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

GO

/* © Кейсистемс (Keysystems), 2010 Процедура формирования строк и значений формы 0503125 */

CREATE PROCEDURE dbo.RT_CALC_0503125M_ITOG_2015
@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(100),
@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), inn varchar(20), ppp char(3), el_bud char(2), okato char(14), 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, inn, ppp, okato, el_bud, KBK, Code_acc, summa_db, summa_kr, korr_acc, dnd, link, key_prov, tabsource)
select
coalesce(rd1.Str_Val,''), --Наименование
coalesce(rd2.Str_Val,''),	--Инн
substring(coalesce(rd3.Str_Val,''),1,3), -- Глава по БК
coalesce(rd4.Str_Val,''),				 -- Код ОКТМО
substring(coalesce(rd5.Str_Val,''),1,2), -- Код элемента бюджета
--substring(coalesce(rd6.Str_Val,''),1,3), -- АДМ
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(rd6.Str_Val,'')),3)+left(left(ltrim(coalesce(rd7.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(rd6.Str_Val,'')),3)+left(left(ltrim(coalesce(rd7.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(rd6.Str_Val,'')),3)+left(left(ltrim(coalesce(rd7.Str_Val,'')),3)+'00000000000000',14)
when @table = 3 and right(rtrim(@cAccount),8) in ('30111000','30131000','30141000','30151000','30121000')
then right('000'+rtrim(coalesce(rd6.Str_Val,'')),3)+left(left(ltrim(coalesce(rd7.Str_Val,'')),14)+'00000000000000',14)
when @table = 3 and right(rtrim(@cAccount),8) in ('30111810','30131810', '30111710', '30121710', '30121810')
then right('000'+rtrim(coalesce(rd6.Str_Val,'')),3)+left(left(ltrim(coalesce(rd7.Str_Val,'')),10)+'00000000000000',14)
else right('000'+rtrim(coalesce(rd6.Str_Val,'')),3)+left(left(ltrim(coalesce(rd7.Str_Val,'')),4)+'00000000000000',14)
end,
case WHEN right(rtrim(@cAccount),8) in ('30406000')
THEN CASE WHEN isnull(rd8.Float_Val,0.00) <> 0
THEN LEFT(@cAccount,6) + '830'
ELSE LEFT(@cAccount,6) + '730' END 
ELSE @cAccount
END,
isnull(rd8.Float_Val,0.00),
isnull(rd9.Float_Val,0.00),
substring(coalesce(rd10.Str_Val,''),1,9),
case when cast(rtrim(isnull(rd15.Str_Val,'')) as varchar) not in (0,1) then NULL else cast(rtrim(isnull(rd15.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 rd15 on rd15.link_sf = @LSF and rd15.Code_Row = srows.Code_Row and 15 = (select Orders from dbo.report_coloumns where link_col = rd15.link_col) and rd15.link_col = (select link_col from dbo.report_coloumns where Orders = 15 and Link_Table = @iLink_Table)

-- исключение, добавить сумму по '30406000'
INSERT @table2 (Name_bp, INN, ppp, el_bud, okato, KBK, Code_Acc, summa_db, summa_kr,
       korr_acc, dnd, link, key_prov, tabsource)
SELECT Name_bp, INN, 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, INN, ppp, okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, link, key_prov, tabsource)
select
coalesce(rd1.Str_Val,''),
coalesce(rd2.Str_Val,''),
substring(coalesce(rd3.Str_Val,''),1,3),
substring(coalesce(rd4.Str_Val,''),1,8),
substring(coalesce(rd5.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(rd6.Str_Val,'')),3)+right('0000'+rtrim(coalesce(rd7.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') and @cSGU in ('710','810')) or
(@cSinth = '302' and @cAnalit = '51' and @cSGU = '830'))
then right('0000000'+rtrim(coalesce(rd8.Str_Val,'')),7) + '000'
else '0000000000'
end,
case WHEN right(rtrim(@cAccount),8) in ('30406000')
THEN CASE WHEN isnull(rd10.Float_Val,0.00) <> 0
THEN LEFT(@cAccount,6) + '830'
ELSE LEFT(@cAccount,6) + '730' END 
ELSE @cAccount
END,
isnull(rd10.Float_Val,0.00),
isnull(rd11.Float_Val,0.00),
substring(coalesce(rd12.Str_Val,''),1,9),
case when cast(rtrim(isnull(rd17.Str_Val,'')) as varchar) not in (0,1) then NULL else cast(rtrim(isnull(rd17.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)
left join #report_dinamics as rd17 on rd17.link_sf = @LSF and rd17.Code_Row = srows.Code_Row and 17 = (select Orders from dbo.report_coloumns where link_col = rd17.link_col) and rd17.link_col = (select link_col from dbo.report_coloumns where Orders = 17 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 (INN, ppp,KBK,Code_Acc,summa_db,link)
select INN, 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 INN, ppp,KBK,Code_Acc
-- итоговые по неденежным
insert into @table2 (INN, 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 INN, 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 INN, 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 (INN, 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 INN, 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 INN, 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 (INN, ppp,KBK,Code_Acc,summa_kr,link)
select INN, 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 INN, ppp,KBK,Code_Acc
-- итоговые по неденежным
insert into @table2 (INN, 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 INN, 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 INN, 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 (INN, ppp,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_db,link)
select INN, 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 INN, ppp, el_bud,okato,Code_Acc
-- итоговые по неденежным
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select INN, 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 INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select INN, 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 INN, 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 INN, 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 (/*INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_db,link)
select INN, 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 INN, ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
--insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
if @code_form like '425_' begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp, el_bud,okato,Code_Acc,summa_db,link)
select INN, 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 INN, ppp, el_bud,okato,Code_Acc

end
-- итоговые по неденежным
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select INN, 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.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select INN, 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 INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc
end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_db,link)     select INN, 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 INN, ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select INN, 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 INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_db,link, kbk)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_db,link)
select INN, 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 INN, 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 ('31','41') and @cSGU = '000') or
(@cSinth = '302' and @cAnalit = '51' and @cSGU = '000' AND @code_form LIKE '%125%') 
or (@cSinth = '301' and @cAnalit in ('21') and @cSGU = '000' AND @code_form LIKE '%125%')
begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,link)
select INN, 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 INN, 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') 
or (@cSinth = '301' and @cAnalit in ('21') and @cSGU = '000')
-- итоговые. в том числе по номеру (коду) счета
IF @code_form LIKE '%425%'
   insert into @table2 (INN, ppp,el_bud,okato,Code_Acc,summa_kr,link)
   select INN, 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 INN, ppp,el_bud,okato,Code_Acc


-- 301X1000 ####################################################################################################
if (@cSinth = '301' and @cAnalit in ('11') and @cSGU = '000') 
-- итоговые. в том числе по номеру (коду) счета
IF @code_form LIKE '%125%'
   insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,link)
   select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc
ELSE
   insert into @table2 (INN, ppp,el_bud,okato,Code_Acc,summa_kr,link)
   select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_kr,link)
select INN, 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 INN, ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
if @code_form like '425_' begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_kr,link)
select INN, 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 INN, ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
if @code_form like '425_' begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc
end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_kr,link)
select INN, 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 INN, ppp,el_bud,okato,Code_Acc
-- итоговые по неденежным
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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') 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, 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') 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 < 10 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,6,9) then 0.0000
when @i = 7 then coalesce(summa_db,0.0000)
when @i = 8 then coalesce(summa_kr,0.0000)
end),
@str_val =
(case when @i in (7,8) then ''
when @i = 1 then cast(coalesce(Name_bp,'') as varchar (250))
when @i = 2 then cast(coalesce(INN,'') as varchar (20))
when @i = 3 then cast(coalesce(ppp,'') as varchar (250))
when @i = 4 then cast(coalesce(okato,'') as varchar (250))
when @i = 5 then cast(coalesce(el_bud,'') as varchar (250))
when @i = 6 then cast(coalesce(KBK,'')+coalesce(Code_acc,'') as varchar (250))
when @i = 9 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_2015] 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', '111' )


INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '117',
	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 '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', '113')

--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_NUO_DGH_FILL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_NUO_DGH_FILL]
GO

CREATE PROCEDURE DBO.SD_NUO_DGH_FILL
	@varKSdDate datetime = NULL,
	@DEP_LINK INT = NULL,
	@MODE TINYINT = 1,
	@BUFFER VARCHAR(20) = NULL
AS 
DECLARE @varKSDateB datetime, @varKSDateE datetime
set @varKSDateB = dbo.DateBeginOfMonth(@varKSdDate)
set @varKSDateE = dbo.DateEndOfMonth(@varKSdDate)

DECLARE @EKR213 INT
SET @EKR213 = (SELECT TOP 1 LINK FROM DICTIONARY_ITEM WHERE CODE = '213')

CREATE TABLE #DOG(LINK_DOG INT)

IF @BUFFER IS NOT NULL
	INSERT INTO #DOG (LINK_DOG)
	SELECT LINK FROM dbo.BUFFER WITH (NOLOCK) WHERE ID = @BUFFER AND SID = SUSER_SID()

DECLARE @EKR211 INT
SET @EKR211 = (SELECT TOP 1 LINK FROM DICTIONARY_ITEM WHERE CODE = '211')

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

--Инвалиды и процент по ним
CREATE TABLE #INV (LINK INT)
INSERT  INTO #INV (LINK)
SELECT
	I.PERS_LINK
FROM	
	dbo.PERS_INVALID I
WHERE
	(YEAR(@varKSDateE) * 100 + MONTH(@varKSDateE)) BETWEEN YEAR(ISNULL(I.DATE_BEGIN,@varKSDateE)) * 100 + MONTH(ISNULL(I.DATE_BEGIN,@varKSDateE))
											AND YEAR(ISNULL(I.DATE_END,@varKSDateE)) * 100 + MONTH(ISNULL(I.DATE_END,@varKSDateE))

--1) РЕЕСТР ДОГОВОРОВ ДЛЯ РАСЧЁТА
CREATE TABLE #DGH(
	PERS_LINK INT,
	FIO VARCHAR(254),
	DATE1 DATETIME,
	DATE2 DATETIME,
	SUMMA NUMERIC(18,2),
	SUMMA_ADD NUMERIC(18,2),
	LINK_PAYS INT,
	CODE_PAYS VARCHAR(10),
	NAME_PAYS VARCHAR(60),
	LINK INT, 
	NUMBER VARCHAR(10),
	[DATE] DATETIME,
	PAYMENT TINYINT,
	VZNOS TINYINT,
	FLAG_NALOG  TINYINT,
	FLAG_ESN TINYINT,
	FLAG_TRAVMA  TINYINT,
	BIRTHDATE DATETIME, 
	SEX TINYINT,
	DATE_BEGIN DATETIME,
	DATE_END DATETIME,
	SUMMA_CALC NUMERIC(18,2),
	LINK_VKR INT,
	NAME_VKR VARCHAR(254),
	LINK_EKR INT,
	CODE_EKR VARCHAR(3),
	LINK_EKR3 INT,
	CODE_EKR3 VARCHAR(3),
	KATEG TINYINT,
	RESIDENT TINYINT
)
INSERT INTO #DGH(
	PERS_LINK,FIO,DATE1,DATE2,SUMMA,SUMMA_ADD,LINK_PAYS,CODE_PAYS,NAME_PAYS,LINK,NUMBER,[DATE],
	PAYMENT,VZNOS,FLAG_NALOG,FLAG_ESN,FLAG_TRAVMA,BIRTHDATE,SEX,DATE_BEGIN,DATE_END,SUMMA_CALC,
	LINK_VKR,NAME_VKR,LINK_EKR,CODE_EKR,LINK_EKR3,CODE_EKR3,KATEG,RESIDENT)
SELECT 
	SRD.PERS_LINK,FIO,DATE1,DATE2,
	[SUMMA] = SRD.SUMMA, 
	[SUMMA_ADD] =  0,
	LINK_PAYS,CODE_PAYS,NAME_PAYS,
	SRD.LINK, SRD.NUMBER,
	SRD.[DATE],PAYMENT,
	VZNOS,FLAG_NALOG,FLAG_ESN,FLAG_TRAVMA,
	BIRTHDATE, SEX,
	[DATE_BEGIN] =(case when date1<@varKSDateB then @varKSDateB else date1 end),
	[DATE_END] =(case when date2>@varKSDateE then @varKSDateE else date2 end),
	[SUMMA_CALC] = SRD.SUMMA *(case when PAYMENT=2 then ((datediff(d,(case when DATE1>@varKSDateB then DATE1 else @varKSDateB end),(case when DATE2<@varKSDateE then DATE2 else @varKSDateE end))+1)/(datediff(d,@varKSDateB,@varKSDateE)+1)) else 1 end),
	[LINK_VKR]=SRD.LINK_KBK,
	[NAME_VKR]= SRD.CODE_KBK,
	[LINK_EKR]= P.link_ekr,
	[CODE_EKR]= DI.CODE,
	[LINK_EKR3]= CASE WHEN P.link_ekr = @EKR211 THEN @EKR213 ELSE P.link_ekr END,
	[CODE_EKR3]= CASE WHEN P.link_ekr = @EKR211 THEN '213' ELSE DI.CODE END,
	KATEG = (CASE WHEN I.LINK IS NULL THEN 1 ELSE 3 END), -- SELECT * FROM SA_PFR_KATEG
	SRD.RESIDENT
FROM 
	dbo.SALARY_REESTR_DGH SRD 
	INNER JOIN dbo.PAYS P ON SRD.LINK_PAYS = P.LINK
	LEFT JOIN dbo.DICTIONARY_ITEM DI ON DI.LINK = P.LINK_EKR
	LEFT JOIN #INV I ON I.LINK = SRD.PERS_LINK
WHERE 
	((date1<=@varKSDateE AND date2>=@varKSDateB  and @varKSdDate is not null ) or @varKSdDate is null )
	AND dep_link = @DEP_LINK
	AND @varKSdDate IS NOT NULL
	AND (@MODE = 1 OR @MODE = 2 AND EXISTS (SELECT * FROM #DOG WHERE LINK_DOG = SRD.LINK))
	

INSERT INTO #DGH(
	PERS_LINK,FIO,DATE1,DATE2,SUMMA,SUMMA_ADD,LINK_PAYS,CODE_PAYS,NAME_PAYS,LINK,NUMBER,[DATE],
	PAYMENT,VZNOS,FLAG_NALOG,FLAG_ESN,FLAG_TRAVMA,BIRTHDATE,SEX,DATE_BEGIN,DATE_END,SUMMA_CALC,
	LINK_VKR,NAME_VKR,LINK_EKR,CODE_EKR,LINK_EKR3,CODE_EKR3,KATEG,RESIDENT)
SELECT 
	SRD.PERS_LINK,FIO,DATE1,DATE2,
	[SUMMA] = 0, 
	[SUMMA_ADD] =  SUM(AD.SUMMA),
	LINK_PAYS,CODE_PAYS,NAME_PAYS,
	SRD.LINK, SRD.NUMBER,
	SRD.[DATE],PAYMENT,
	VZNOS,FLAG_NALOG,FLAG_ESN,FLAG_TRAVMA,
	BIRTHDATE, SEX,
	[DATE_BEGIN] = NULL,
	[DATE_END] =NULL,
	[SUMMA_CALC] = 0,
	[LINK_VKR]= 0,
	[NAME_VKR]= '',
	[LINK_EKR]=0,
	[CODE_EKR]= '',
	[LINK_EKR3]=0,
	[CODE_EKR3]= '',
	KATEG = (CASE WHEN I.LINK IS NULL THEN 1 ELSE 3 END), -- SELECT * FROM SA_PFR_KATEG
	SRD.RESIDENT
FROM 
	dbo.SALARY_REESTR_DGH SRD 
	INNER JOIN dbo.SD_NDFL_ADDITION_DOHOD  AD ON AD.DGH_LINK = SRD.LINK AND AD.PERS_TYPE = 2 
	LEFT JOIN #INV I ON I.LINK = SRD.PERS_LINK	
WHERE 
	dep_link = @DEP_LINK
	AND @varKSdDate IS NULL
	AND (@MODE = 1 OR @MODE = 2 AND EXISTS (SELECT * FROM #DOG WHERE LINK_DOG = SRD.LINK))
GROUP BY
	SRD.PERS_LINK,FIO,DATE1,DATE2,
	LINK_PAYS,CODE_PAYS,NAME_PAYS,
	SRD.LINK, SRD.NUMBER,
	SRD.[DATE],PAYMENT,
	VZNOS,FLAG_NALOG,FLAG_ESN,FLAG_TRAVMA,
	BIRTHDATE, SEX, I.LINK, SRD.RESIDENT

IF @MODE = 1 BEGIN
	SELECT
		[NAME_DOG] = '№ '+rtrim(NUMBER)+' от '+convert(varchar(20),DATE,104),
		*
	FROM #DGH ORDER BY FIO
	RETURN 0
END
	
--2) СПИСОК ВИДОВ ВЗНОСОВ НА ДАННЫЙ ПЕРИОД	
CREATE TABLE #PAYS3	(LINK INT)

INSERT INTO #PAYS3 (LINK)
SELECT 
	T.REF_PAY
FROM
	dbo.MINROT M 
	INNER JOIN dbo.DICTIONARY_MROT_TABLE4 T ON T.LINK_MINROT = M.LINK
WHERE
	M.LINK = ( SELECT TOP 1 M2.LINK FROM dbo.MINROT M2 WHERE M2.PERIOD <= @varKSDateE ORDER BY M2.PERIOD DESC )

--Травматизм
INSERT INTO #PAYS3 (LINK)
SELECT LINK FROM dbo.PAYS P
WHERE 
	[OBJECT] = 3 AND WAY_CALC = 5
	AND NOT EXISTS (SELECT * FROM #PAYS3 PP WHERE PP.LINK = P.LINK)

DECLARE @PERC_TRAVM_IVALID NUMERIC(18,2)
SET @PERC_TRAVM_IVALID = ISNULL((SELECT TOP 1 MP.summa FROM dbo.MINROT_PAYS MP WHERE LINK_MINROT = (SELECT TOP 1 LINK FROM dbo.MINROT WHERE PERIOD<=@varKSDateE ORDER BY PERIOD DESC)),0)

--Базовые начисления
CREATE TABLE #TR(LINK_TAX INT, LINK_PAYS INT)
INSERT INTO #TR(LINK_TAX, LINK_PAYS)
SELECT DISTINCT R.LINK_TAX, R.LINK_PAYS
FROM
	dbo.TAX_REF R
	INNER JOIN dbo.PAYS P ON P.LINK = R.LINK_TAX
WHERE	
	(P.OBJECT = 2) 
	or 
	(P.OBJECT = 3 AND EXISTS (SELECT * FROM #PAYS3 P3 WHERE P3.LINK = P.LINK))	

--
DECLARE @BY DATETIME
SET @BY = dbo.DateBeginOfYear(@varKSDateB)

CREATE TABLE #DICT_VICHET (LINK_DOG INT, LINK_DED INT, PREDEL NUMERIC(18,2), SUMMA NUMERIC(18,2), DATE1 DATETIME, DATE2 DATETIME, MONS INT)

INSERT INTO #DICT_VICHET (LINK_DOG, LINK_DED, PREDEL, SUMMA, DATE1, DATE2)
SELECT 
	LINK_DGH, DED_LINK, SD.PREDEL, SD.SUMMA, 
	
	DATE1 = CASE WHEN (CASE WHEN D.DATE1 < SRD.DATE1 THEN SRD.DATE1 ELSE D.DATE1 END) <= @BY
				THEN @BY
				ELSE (CASE WHEN D.DATE1 < SRD.DATE1 THEN SRD.DATE1 ELSE D.DATE1 END)
			END, 
	
	DATE2 = CASE WHEN (CASE WHEN D.DATE2 > SRD.DATE2 THEN SRD.DATE2 ELSE D.DATE2 END) > @varKSDateE
				THEN @varKSDateE
				ELSE (CASE WHEN D.DATE2 > SRD.DATE2 THEN SRD.DATE2 ELSE D.DATE2 END)
			END
FROM
	#DOG A 
	INNER JOIN dbo.SALARY_REESTR_DGH SRD ON SRD.LINK = A.LINK_DOG
	INNER JOIN dbo.EMPL_DED D ON D.LINK_DGH = A.LINK_DOG
	INNER JOIN dbo.Salary_deductions(@varKSDateE) SD ON SD.REF_PAY = D.DED_LINK
WHERE
	(CASE WHEN D.DATE1 < SRD.DATE1 THEN SRD.DATE1 ELSE D.DATE1 END)<=@varKSDateE 
	AND 
	(CASE WHEN D.DATE2 > SRD.DATE2 THEN SRD.DATE2 ELSE D.DATE2 END)>=@varKSDateB

UPDATE #DICT_VICHET
SET MONS = MONTH(DATE2) - MONTH(DATE1) + 1

---
CREATE TABLE #TAX (	
	ID INT IDENTITY(1,1), ORDERS INT,
	LINK_DOG INT, SUMMA_BASE NUMERIC(18,2), PERS_LINK INT, LINK INT, CODE VARCHAR(10), 
	NAME VARCHAR(254), WAY_CALC TINYINT, [PERCENT] NUMERIC(18,4), [OBJECT] INT,
	BASE_YEAR NUMERIC(18,2), SUMMA_YEAR NUMERIC(18,2), SUMMA_OLD NUMERIC(18,2), SUMMA NUMERIC(18,2), LINK_SFIN INT)

INSERT INTO #TAX (LINK_DOG, SUMMA_BASE, PERS_LINK, LINK, CODE, NAME, WAY_CALC, [PERCENT], [OBJECT])	
SELECT
	LINK_DOG = D.LINK,
	SUMMA_BASE = ISNULL(SUMMA,0) + ISNULL(SUMMA_ADD,0),
	PERS_LINK = D.PERS_LINK,
	P.LINK,
	P.CODE,
	P.NAME,
	P.WAY_CALC,
	[percent] =	(CASE WHEN P.WAY_CALC NOT IN (6,7,8,9) THEN 
					(CASE WHEN 
							WAY_CALC = 5 --ФСС ТРАВМАТИЗМ
							AND 
							(CASE WHEN ISNULL(D.KATEG,0) > (ISNULL(F.ENVD,0) + 1) THEN ISNULL(D.KATEG,0) ELSE (ISNULL(F.ENVD,0) + 1) END) = 3 
						THEN
							@PERC_TRAVM_IVALID
					ELSE 
						ISNULL((	SELECT TOP 1 DR.[percent] 
							from dbo.dictionary_range DR
							where 
								(	
									DR.TARIF = (CASE WHEN ISNULL(D.KATEG,0) > (ISNULL(F.ENVD,0) + 1) THEN ISNULL(D.KATEG,0) ELSE (ISNULL(F.ENVD,0) + 1) END)
									OR --Для подоходного налога по общему тарифу всегда
									DR.TARIF = 1 
									AND 
									EXISTS (SELECT * FROM dbo.PAYS P1 WHERE DR.LINK_PAYS = P1.LINK AND P1.[OBJECT] = 2 AND P1.WAY_CALC IN (4,5,6)) 
								)
								AND DR.LINK_PAYS = P.LINK and [DATE]<=@varKSDateE order by DR.[DATE] desc, DR.PREDEL asc
						),0)  
									
					END)	
			ELSE
				ISNULL((SELECT TOP 1 (CASE WHEN 
								(CASE 
									WHEN YEAR(BIRTHDATE)<=(CASE WHEN D.SEX = 1 THEN 1952 ELSE 1956 END) THEN 1 
									WHEN (YEAR(BIRTHDATE)>(CASE WHEN D.SEX = 1 THEN 1952 ELSE 1956 END) AND YEAR(BIRTHDATE)<1967) THEN 2 
									ELSE 3 
								END) = 1 
								THEN PERCENT1 
							WHEN 
								(CASE 
									WHEN YEAR(BIRTHDATE)<=(CASE WHEN D.SEX = 1 THEN 1952 ELSE 1956 END) THEN 1 
									WHEN (YEAR(BIRTHDATE)>(CASE WHEN D.SEX = 1 THEN 1952 ELSE 1956 END) AND YEAR(BIRTHDATE)<1967) THEN 2 
									ELSE 3 
								END) = 2  
								THEN PERCENT2 
							ELSE PERCENT3 END) 
					FROM 
						DBO.DICTIONARY_RANGE_PF
					WHERE 
							TARIF = (CASE WHEN ISNULL(D.KATEG,0) > (ISNULL(F.ENVD,0) + 1) THEN ISNULL(D.KATEG,0) ELSE (ISNULL(F.ENVD,0) + 1) END) 
							AND SpecO IS NULL
							AND LINK_PAYS = P.LINK 
							AND DATE<=@varKSDateE 
					ORDER BY DATE DESC, PREDEL ASC),0)  
			 END),
	P.[OBJECT]
FROM 
	#DGH D
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = D.LINK_VKR
	INNER JOIN #TR R ON R.LINK_PAYS = D.LINK_PAYS
	INNER JOIN dbo.PAYS P ON P.LINK = R.LINK_TAX
WHERE
	(
		P.[OBJECT] = 2 AND D.FLAG_NALOG = 1 AND (D.RESIDENT = 1 AND P.WAY_CALC = 4 OR D.RESIDENT <> 1 AND P.WAY_CALC = 5)
		OR 
		P.[OBJECT] = 3 
				AND (P.WAY_CALC = 5 AND D.FLAG_TRAVMA = 1 OR P.WAY_CALC = 2 AND D.VZNOS = 1 OR P.WAY_CALC IN (1,3,4,6,7,8,9) AND D.FLAG_ESN = 1)
				AND EXISTS (SELECT * FROM #PAYS3 P3 WHERE P3.LINK = P.LINK)
	)
ORDER BY
	P.OBJECT, D.LINK	

--- Прочие удержания по договорникам
INSERT INTO #TAX (LINK_DOG, SUMMA_BASE, PERS_LINK, LINK, CODE, NAME, WAY_CALC, [PERCENT], [OBJECT], LINK_SFIN)	
SELECT
	LINK_DOG = D.LINK,
	SUMMA_BASE = 
			CASE WHEN P.WAY_CALC IN (2,3) THEN
				ISNULL(D.SUMMA,0) * ISNULL( (SELECT MAX(1) FROM dbo.TAX_REF G WHERE G.LINK_TAX = T.LINK_TAX AND G.LINK_PAYS = D.LINK_PAYS) ,0)
			ELSE
				0
			END,
	PERS_LINK = D.PERS_LINK,
	P.LINK,
	P.CODE,
	P.NAME,
	P.WAY_CALC,	
	[percent] =	T.SUMMA,
	P.[OBJECT],
	(CASE WHEN ISNULL(T.LINK_VKR,0) = 0 THEN D.LINK_VKR ELSE T.LINK_VKR END)
FROM 
	#DGH D
	INNER JOIN dbo.SD_EMPL_TAX T ON T.LINK_DGH = D.LINK
	INNER JOIN dbo.PAYS P ON P.LINK = T.LINK_TAX
WHERE
	P.[OBJECT] = 2
ORDER BY
	P.CODE, D.LINK

--3) РАНЕЕ НАЧИСЛЕННЫЕ ДОХОДЫ,ВЗНОСЫ И НАЛОГИ
CREATE TABLE #OLD (MON INT, PERS_LINK INT, LINK_DOG INT, LINK INT, SUMMA_D NUMERIC(18,2), SUMMA_N NUMERIC(18,2))

INSERT INTO #OLD (MON, PERS_LINK, LINK_DOG, LINK, SUMMA_D, SUMMA_N)
SELECT 
	MONTH(D.[DATE]),
	T2.PERS_LINK,
	D.LINK,
	T2.LINK_PAY,
	SUMMA_D = SUM(T2.SUMMA_BASE),
	SUMMA_N = SUM(T2.SUMMA)
FROM
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DGH_TABLE T2 ON T2.LINK_UP = D.LINK 
	INNER JOIN dbo.PAYS P ON P.LINK = T2.LINK_PAY
WHERE 
	D.LINK_DEP = @DEP_LINK
	AND
	D.FLAG_JC = 1
	AND
	T2.[OBJECT] = 2	
	AND
	P.[OBJECT] = 2 AND P.WAY_CALC IN (4,5,6)
	AND
	YEAR(D.[DATE]) = YEAR(@varKSDateE)
	AND
	MONTH(D.[DATE]) <= MONTH(@varKSDateE)
GROUP BY
	MONTH(D.[DATE]),
	T2.PERS_LINK,
	D.LINK,
	T2.LINK_PAY
	
INSERT INTO #OLD (MON, PERS_LINK, LINK_DOG, LINK, SUMMA_D, SUMMA_N)
SELECT 
	MONTH(D.[DATE]),
	T2.PERS_LINK,
	D.LINK,
	T2.LINK_PAY,
	SUMMA_D = SUM(T2.SUMMA_BASE),
	SUMMA_N = SUM(T2.SUMMA)
FROM
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DGH_TABLE T2 ON T2.LINK_UP = D.LINK 
	INNER JOIN dbo.PAYS P ON P.LINK = T2.LINK_PAY
WHERE 
	D.LINK_DEP = @DEP_LINK
	AND
	D.FLAG_JC = 1
	AND
	T2.[OBJECT] = 3	
	AND
	P.[OBJECT] = 3 AND EXISTS (SELECT * FROM #PAYS3 P3 WHERE P3.LINK = P.LINK)
	AND
	YEAR(D.[DATE]) = YEAR(@varKSDateE)
	AND
	MONTH(D.[DATE]) <= MONTH(@varKSDateE)
GROUP BY
	MONTH(D.[DATE]),
	T2.PERS_LINK,
	D.LINK,
	T2.LINK_PAY	

--4) РАСЧЁТ НАЛОГОВ
--Определение базы с начала года	
UPDATE T SET 
	T.BASE_YEAR =	(
					ISNULL((SELECT SUM(O.SUMMA_D) FROM #OLD O WHERE O.PERS_LINK = T.PERS_LINK AND O.LINK = T.LINK),0)
					+ ISNULL((SELECT SUM(N.SUMMA_BASE) FROM #TAX N WHERE N.PERS_LINK = T.PERS_LINK AND N.LINK = T.LINK),0)
					) 
					* 
					(CASE WHEN ISNULL((SELECT SUM(N.SUMMA_BASE) FROM #TAX N WHERE N.PERS_LINK = T.PERS_LINK AND N.LINK = T.LINK),0) > 0
						THEN T.SUMMA_BASE / ISNULL((SELECT SUM(N.SUMMA_BASE) FROM #TAX N WHERE N.PERS_LINK = T.PERS_LINK AND N.LINK = T.LINK),0)
						ELSE 0
					END)	
	,T.SUMMA_OLD = ISNULL((SELECT SUM(O.SUMMA_N) FROM #OLD O WHERE O.PERS_LINK = T.PERS_LINK AND O.LINK = T.LINK),0)
					* 
					(CASE WHEN ISNULL((SELECT SUM(N.SUMMA_BASE) FROM #TAX N WHERE N.PERS_LINK = T.PERS_LINK AND N.LINK = T.LINK),0) > 0
						THEN T.SUMMA_BASE / ISNULL((SELECT SUM(N.SUMMA_BASE) FROM #TAX N WHERE N.PERS_LINK = T.PERS_LINK AND N.LINK = T.LINK),0)
						ELSE 0
					END)	
FROM 
	#TAX T
WHERE
	T.[OBJECT] = 2 AND T.WAY_CALC IN (4,5,6)
	OR
	T.[OBJECT] = 3

--
CREATE TABLE #DOXOD (LINK_PERS INT, MON INT, SUMMA NUMERIC(18,2), SUMMA2 NUMERIC(18,2))
INSERT INTO #DOXOD (LINK_PERS, MON, SUMMA, SUMMA2)
SELECT PERS_LINK, MON, SUM(SUMMA_D), 0
FROM
	(
	SELECT PERS_LINK, MON, SUMMA_D FROM #OLD O INNER JOIN dbo.PAYS P ON P.LINK = O.LINK WHERE P.[OBJECT] = 2 AND P.WAY_CALC IN (4,5,6)
	UNION ALL	
	SELECT PERS_LINK, MON = MONTH(@varKSdDate), SUMMA_BASE FROM #TAX T INNER JOIN dbo.PAYS P ON P.LINK = T.LINK WHERE P.[OBJECT] = 2 AND P.WAY_CALC IN (4,5,6)
	) T
GROUP BY PERS_LINK, MON

--
UPDATE D
SET SUMMA2 = (SELECT SUM(SUMMA) FROM #DOXOD D2 WHERE D2.LINK_PERS = D.LINK_PERS AND D2.MON <= D.MON)
FROM #DOXOD D

--
DELETE FROM [dbo].[SAL_DED_MONTH]
WHERE EXISTS (SELECT * FROM #DGH H WHERE H.LINK = [dbo].[SAL_DED_MONTH].[LINK_DGH])

--
INSERT INTO [dbo].[SAL_DED_MONTH] (REF_DED, SUMMA, DATE_DED, LINK_VKR, LINK_EKR, [TYPE], KOEF_VKR, KOL, LINK_DGH)
SELECT 
	REF_DED = V.LINK_DED, 
	V.SUMMA,
	DATE_DED = M.DATE_BEGIN,
	LINK_VKR = H.LINK_VKR,
	LINK_EKR = H.LINK_EKR,
	[TYPE] = 1,
	KOEF_VKR = 1,
	KOL = 1,
	LINK_DGH = H.LINK
FROM
	dbo.MONTHS_EX (@BY, @varKSDateE) M
	INNER JOIN #TAX T ON 1=1
	INNER JOIN #DGH H ON H.LINK = T.LINK_DOG
	INNER JOIN #DICT_VICHET V ON T.LINK_DOG = V.LINK_DOG
	LEFT JOIN #DOXOD D ON D.LINK_PERS = T.PERS_LINK AND D.MON = M.M
WHERE
	T.[OBJECT] = 2 AND T.WAY_CALC = 4
	AND
	M.M BETWEEN MONTH(V.DATE1) AND MONTH(V.DATE2)
	AND
	(CASE WHEN ISNULL(D.SUMMA2,0) <= ISNULL(V.PREDEL,0) OR ISNULL(V.PREDEL,0) = 0 THEN ISNULL(V.SUMMA,0) ELSE 0 END) > 0

--определение вычетов с начала года
CREATE TABLE #SUM_VYCH (LINK_DOG INT, LINK INT, SUMMA_YEAR NUMERIC(18,2), SUMMA_M NUMERIC(18,2))
INSERT INTO #SUM_VYCH (LINK_DOG, LINK, SUMMA_YEAR, SUMMA_M)
SELECT 
	T.LINK_DOG,
	T.LINK,
	SUM_VICH = (SELECT SUM(SDM.SUMMA) FROM 
					[dbo].[SAL_DED_MONTH] SDM 
					INNER JOIN dbo.[REESTR_DGH] RD ON SDM.LINK_DGH = RD.LINK
				WHERE 
					RD.DEP_LINK = @DEP_LINK AND T.PERS_LINK = RD.PERS_LINK
					AND YEAR(SDM.DATE_DED) =YEAR(@varKSDateE) AND MONTH(SDM.DATE_DED) <= MONTH(@varKSDateE)),
	SUMMA_M = (SELECT SUM(SDM.SUMMA) FROM 
					[dbo].[SAL_DED_MONTH] SDM 
					INNER JOIN dbo.[REESTR_DGH] RD ON SDM.LINK_DGH = RD.LINK
				WHERE 
					RD.DEP_LINK = @DEP_LINK AND T.PERS_LINK = RD.PERS_LINK
					AND YEAR(SDM.DATE_DED) =YEAR(@varKSDateE) AND MONTH(SDM.DATE_DED) = MONTH(@varKSDateE))
FROM 
	#TAX T
WHERE
	T.[OBJECT] = 2 AND T.WAY_CALC = 4
GROUP BY
	T.LINK_DOG, T.PERS_LINK, T.LINK

--Определенеи налога с начала года
UPDATE T SET 
	T.SUMMA_YEAR = 
		CASE WHEN P.OBJECT = 2 THEN
			ROUND((T.BASE_YEAR - ISNULL(V.SUMMA_YEAR,0)) * ISNULL(T.[PERCENT],0) / 100,0)
		ELSE
			T.BASE_YEAR * ISNULL(T.[PERCENT],0) / 100
		END
FROM 
	#TAX T
	INNER JOIN dbo.PAYS P ON P.LINK = T.LINK
	LEFT JOIN #SUM_VYCH V ON V.LINK_DOG = T.LINK_DOG

--Определенеи налога за месяц
UPDATE T SET 
	T.SUMMA = T.SUMMA_YEAR - T.SUMMA_OLD
FROM 
	#TAX T

--ОКРУГЛЯЕМ МЕСЯЧНЫЙ НАЛОГ ДО КОПЕЕК
CREATE TABLE #TAX1 (PERS_LINK INT,LINK INT,SUMMA NUMERIC(18,2))
INSERT INTO #TAX1 (PERS_LINK,LINK,SUMMA)
SELECT T.PERS_LINK, T.LINK, SUM(T.SUMMA) 
FROM #TAX T INNER JOIN dbo.PAYS P ON T.LINK = P.LINK
WHERE P.[OBJECT] = 2 AND P.WAY_CALC IN (4,5,6)
GROUP BY T.PERS_LINK, T.LINK

--Округление НДФЛ за месяц
UPDATE T SET 
	T.SUMMA = CONVERT(NUMERIC(18,0),T.SUMMA)
FROM 
	#TAX T
WHERE	
	T.[OBJECT] = 2 AND T.WAY_CALC IN (4,5,6)
	
--
UPDATE T SET 
	T.SUMMA = 
		CASE WHEN T.WAY_CALC = 1
			THEN T.[PERCENT] --T.[PERCENT] СОДЕРЖИТ СУММУ
			ELSE SUMMA_BASE * T.[PERCENT] / 100 --T.[PERCENT] СОДЕРЖИТ ПРОЦЕНТ
		END,
	BASE_YEAR = 0,
	SUMMA_YEAR = 0,
	SUMMA_OLD = 0		
FROM 
	#TAX T
WHERE
	T.[OBJECT] = 2 AND T.WAY_CALC IN (1,2,3)	


CREATE TABLE #TAX2 (PERS_LINK INT,LINK_DOG INT,LINK INT,SUMMA NUMERIC(18,2))
INSERT INTO #TAX2 (PERS_LINK, LINK_DOG, LINK, SUMMA)
SELECT PERS_LINK, MAX(LINK_DOG), T.LINK, SUM(SUMMA) 
FROM #TAX T INNER JOIN dbo.PAYS P ON T.LINK = P.LINK
WHERE P.[OBJECT] = 2 AND P.WAY_CALC IN (4,5,6)
GROUP BY T.PERS_LINK, T.LINK

UPDATE T SET 
	T.SUMMA = CONVERT(NUMERIC(18,0), ISNULL(T.SUMMA,0) + ISNULL((SELECT T1.SUMMA FROM #TAX1 T1 WHERE T2.PERS_LINK = T1.PERS_LINK AND T2.LINK = T1.LINK),0) - ISNULL(T2.SUMMA,0))
FROM 
	#TAX T
	INNER JOIN #TAX2 T2 ON T.LINK_DOG = T2.LINK_DOG AND T.LINK = T2.LINK
	
DECLARE @Cur1 CURSOR
DECLARE @ID INT, @OBJECT INT, @OBJECT2 INT, @NEXT INT
SELECT @NEXT = 0, @OBJECT2 = 0
SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT ID, OBJECT FROM #TAX ORDER BY ID

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @ID, @OBJECT
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		IF @OBJECT <> @OBJECT2 BEGIN
			SET @NEXT = 1
			SET @OBJECT2 = @OBJECT
		END			
		ELSE
			SET @NEXT = @NEXT + 1
		
		UPDATE #TAX SET ORDERS = @NEXT WHERE ID = @ID

	END

	FETCH NEXT FROM @Cur1 INTO @ID, @OBJECT
END

CLOSE @Cur1
DEALLOCATE @Cur1


SELECT
	T.ORDERS,
	D.LINK, D.PERS_LINK, D.FIO, 
	LINK_VKR = CASE WHEN P.[OBJECT] = 3 THEN ISNULL(SF.LINK_SS_SFIN,D.LINK_VKR) ELSE D.LINK_VKR END,
	NAME_VKR = CASE WHEN P.[OBJECT] = 3 THEN ISNULL(SF2.CODE,D.NAME_VKR) ELSE D.NAME_VKR END,
	LINK_VKR2 = D.LINK_VKR, 
	NAME_VKR2 = D.NAME_VKR, 
	D.LINK_EKR, D.CODE_EKR,
	LINK_PAY = P.LINK, CODE_PAY = P.CODE, NAME_PAY = P.NAME, P.[OBJECT],
	T.BASE_YEAR, T.SUMMA_BASE, 
	V_SUM_Y = ISNULL(V.SUMMA_YEAR,0), V_SUM_M = ISNULL(V.SUMMA_M,0),
	T.[PERCENT], T.SUMMA_YEAR, T.SUMMA_OLD, T.SUMMA
FROM
	#DGH D 
	INNER JOIN #TAX T ON D.LINK = T.LINK_DOG
	INNER JOIN dbo.PAYS P ON P.LINK = T.LINK
	INNER JOIN dbo.SAL_SFIN SF ON SF.LINK = D.LINK_VKR
	LEFT JOIN dbo.SAL_SFIN SF2 ON SF2.LINK = SF.LINK_SS_SFIN
	LEFT JOIN #SUM_VYCH V ON V.LINK = T.LINK AND V.LINK_DOG = T.LINK_DOG
ORDER BY
	P.[OBJECT], D.FIO	

RETURN 0
	



GO


GRANT EXECUTE ON dbo.[SD_NUO_DGH_FILL] TO PUBLIC

GO


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

GO

CREATE  PROCEDURE dbo.[SD_REP_SVOD]
@varKSdDate1 datetime,
@varKSdDate2 datetime,
@detailed_SFIN int,
@detailed_EKR int,
@status3 tinyint,
@detailed_SUBDIV int = 0, /* Группировать по отделам */
@varKScVal1 CHAR(1), @varKSnOtborLink1 int,
@varKScVal2 CHAR(1), @varKSnOtborLink2 int,
@cVal3 CHAR(1), @nOtborLink3 int, --отбор по подразделениям
@CVAL4 CHAR(1), @NOTBORLINK4 INT	/* ОТБОР КАТЕГОРИЙ ДОЛЖНОСТЕЙ */
as 
begin


	set @varKSdDate1 = dbo.DateBeginOfMonth(@varKSdDate1)
	set @varKSdDate2 = dbo.DateEndOfMonth(@varKSdDate2)
	declare @varKSCountEmpl int, @varKSPeriodStr varchar(50), @varKScOtbor varchar(1000), @varKScOtbor2 varchar(1000), @varKScOtbor3 varchar(8000), @varKScOtbor4 varchar(8000)
	set @varKScOtbor = ''
	----Отбор по ВКР
	CREATE TABLE #VKR (LINK_VKR INT)
	IF LEN(@varKScVal1) <> 0 
		begin 
			INSERT  INTO #VKR
			SELECT RECORD
			FROM OBJECT_VAR_SAL_SFIN WHERE LINK_UP = @varKSnOtborLink1
			set @varKScOtbor = 'Отбор по источникам: '
			
			DECLARE @varKSCurs CURSOR, @varKScNAME varchar(40)
			SET @varKSCurs = CURSOR FORWARD_ONLY
			FOR SELECT [name] = (SELECT RTRIM(LTRIM(CODE)) FROM dbo.SAL_SFIN WHERE LINK = LINK_VKR) FROM #VKR
			OPEN @varKSCurs
			FETCH NEXT FROM @varKSCurs INTO @varKScNAME
			WHILE @@FETCH_STATUS = 0
				BEGIN
					set @varKScOtbor = @varKScOtbor + (CASE WHEN LEN(@varKScOtbor) > 21 then ', ' else ' ' end) +rtrim(@varKScNAME)
					FETCH NEXT FROM @varKSCurs INTO @varKScNAME
				END
			CLOSE @varKSCurs
			DEALLOCATE @varKSCurs
		end
	else 
		INSERT INTO #VKR
		SELECT LINK FROM dbo.SAL_SFIN

	---Отбор по ЭКР
	CREATE TABLE #EKR (LINK INT)
	IF LEN(@varKScVal2) <> 0
	begin
		insert into #ekr (link)
		Select record from dbo.OBJECT_VAR_KOSGU	where LINK_UP = @varKSnOtborLink2
		
		set @varKScOtbor2 = 'Отбор по ЭКР: '
		update #ekr set @varKScOtbor2 = @varKScOtbor2 + ltrim(rtrim(K.code)) + ','
		from #ekr o inner join dbo.kosgu K on o.link = K.link

		set @varKScOtbor2 = left(@varKScOtbor2,len(@varKScOtbor2)-1)

	end
	else
		insert into #ekr (link)
		select link from dbo.kosgu order by CODE
	-----
	DECLARE @SALARY_PROV_OPT4 TINYINT
	SET @SALARY_PROV_OPT4 = dbo.sa_get_option_by_code('SALARY_PROV_OPT4')
	-----

	IF OBJECT_ID('tempdb..#SA_EMPLS') IS NOT NULL
		DROP TABLE #SA_EMPLS

	CREATE TABLE #SA_EMPLS (
		[link] int NOT NULL ,
		[link_empl] int NOT NULL ,
		[tab] varchar(10) NOT NULL ,
		[pers_link] int NOT NULL ,
		[link_kateg] int NULL ,
		[kateg_name] varchar(50) NULL ,
		[razr] int NULL ,
		[num_stake] numeric(4, 2) NULL ,
		[link_type] int NULL ,
		[code_type] varchar(4) NOT NULL ,		
		[subdiv_head] int NULL ,
		[subdiv_code] varchar(5) NULL ,
		[subdiv_name] varchar(254) NULL )
	
	INSERT INTO #SA_EMPLS ([link], [link_empl], [tab], [pers_link], [link_kateg], [kateg_name], [razr], [num_stake], [link_type], [code_type], [subdiv_head], [subdiv_code], [subdiv_name] ) 
	SELECT [link], [link_empl], [tab], [pers_link], [link_kateg], [kateg_name], [razr], [num_stake], [link_type], [code_type], [subdiv_head], [subdiv_code], [subdiv_name] 
	FROM [dbo].[SA_EMPLS_W_FN](DEFAULT,DEFAULT,DEFAULT,DEFAULT)


	CREATE INDEX #TMP_IDX_SA_EMPLS ON #SA_EMPLS (LINK,link_empl)

	IF OBJECT_ID('tempdb..#s_j_c') IS NOT NULL
		DROP TABLE #s_j_c
	
	create table #s_j_c (LINK_EMPL int, TAB_NUM varchar(10), FIO varchar(100), LINK_FACE int, LINK_PAYS int,CODE_PAYS varchar(10),
						 NAME_PAYS varchar(60),TYP_PER tinyint,MONTH_BEGIN int,YEAR_BEGIN int,PERIOD_BEGIN datetime,MONTH_END int ,
						 YEAR_END int,PERIOD_END datetime,[HOURS] numeric(7,2),[DAYS] int,SUMMA_BASE numeric(15,2),PROCENT numeric(15,2),
						 SUMMA numeric(15,2),SUBDIV_HEAD int ,NAME_SUBDIV varchar(254),CODE_SUBDIV varchar(5), 
						 TYP_OPER tinyint, PERS_LINK int ,LINK_VKR int,NAME_VKR varchar(30), LINK_EKR int,CODE_EKR char(4),NAME_EKR varchar(250),
						 LINK_INC int, LINK_DEP int,name_dep varchar(254),link_kateg int,kateg_name varchar(50),razr int,num_stake numeric(5,2),link_type int,
						 code_type varchar(4))

insert into #s_j_c (LINK_EMPL,TAB_NUM,FIO,LINK_FACE,LINK_PAYS,CODE_PAYS,
					NAME_PAYS,TYP_PER,MONTH_BEGIN,YEAR_BEGIN,PERIOD_BEGIN,MONTH_END,
					YEAR_END,PERIOD_END,HOURS,DAYS,SUMMA_BASE,PROCENT,SUMMA,SUBDIV_HEAD,NAME_SUBDIV,CODE_SUBDIV,
					TYP_OPER,PERS_LINK,LINK_VKR,NAME_VKR,LINK_EKR,CODE_EKR,NAME_EKR,
					LINK_INC,LINK_DEP,name_dep,link_kateg,kateg_name,razr,num_stake,link_type,code_type)

SELECT 
	[LINK_EMPL] 	= JC.LINK_EMPL,	
	[TAB_NUM]		= EP.TAB,
	[FIO]			= LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(PR.FM)) + ' ' + LTRIM(RTRIM(PR.IM)) + ' ' + LTRIM(RTRIM(PR.OT)),'Не заполнено'))),100),
	[LINK_FACE] 	= EP.PERS_LINK,
	[LINK_PAYS]		= P.LINK,
	[CODE_PAYS]		= P.CODE,
	[NAME_PAYS]		= P.NAME,
	[TYP_PER]		= P.TYP_PER,
	[MONTH_BEGIN]	= MONTH(JC.PERIOD_BEGIN),
	[YEAR_BEGIN]	= YEAR(JC.PERIOD_BEGIN),
	[PERIOD_BEGIN]	= JC.PERIOD_BEGIN,
	[MONTH_END] 	= MONTH(PERIOD_END),
	[YEAR_END]		= YEAR(PERIOD_END),
	[PERIOD_END] 	= JC.PERIOD_END,
	[HOURS]			= JC.HOURS,
	[DAYS]			= JC.DAYS,
	[SUMMA_BASE]	= JC.SUMMA_BASE,
	JC.PROCENT,
	[SUMMA]			= JC.SUMMA,
	EP.SUBDIV_HEAD,
	[NAME_SUBDIV]	= EP.SUBDIV_NAME,
	[CODE_SUBDIV]	= EP.SUBDIV_CODE,
	[TYP_OPER]  	= P.[OBJECT],
	[PERS_LINK] = JC.PERS_LINK,
	[LINK_VKR] = JC.LINK_VKR,
	[NAME_VKR] = FIN.[CODE],
	[LINK_EKR] = COALESCE(JC.LINK_EKR,P.LINK_EKR),
	[CODE_EKR] = EKR.CODE,
	[NAME_EKR] = EKR.[NAME],
	[LINK_INC] 		= P.LINK_INC,
	[LINK_DEP] = JC.LINK_DEP,
	LEFT(dep.NAME,254) as name_dep,
	link_kateg,
	kateg_name,
	razr = CASE WHEN COALESCE(razr,0) = 0 THEN NULL ELSE razr END,
	num_stake,
	link_type,
	code_type
FROM 
	dbo.CALCULATE_JURNAL JC 
	INNER JOIN dbo.DEPARTMENTS dep ON dep.link = JC.LINK_DEP
	INNER JOIN dbo.PAYS P ON JC.LINK_PAYS = P.LINK
	LEFT JOIN (SELECT distinct DA.LINK_UP, DA.VALUE FROM dbo.DICTION_APP DA inner join dbo.S_OBJECTS so on da.OBJECT = so.link and so.code = 'COLUMN_CODE_T_INC') INC
		on INC.LINK_UP = P.LINK_INC
	LEFT JOIN dbo.DICTION D on D.LINK = P.LINK_INC
	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 = JC.LINK_DOC
	LEFT JOIN #SA_EMPLS EP ON EP.link_empl = JC.LINK_EMPL AND EP.link = COALESCE(JC.LINK_SOVM,0)
	LEFT JOIN dbo.PERSON PR ON PR.LINK = (CASE WHEN JC.LINK_EMPL IS NULL THEN JC.PERS_LINK ELSE EP.PERS_LINK END)
	LEFT JOIN dbo.SAL_SFIN FIN on JC.LINK_VKR = FIN.LINK
	LEFT JOIN dbo.KOSGU EKR on COALESCE(JC.LINK_EKR,P.LINK_EKR) = EKR.LINK
WHERE
	JC.PERIOD_BEGIN between @varKSdDate1 and @varKSdDate2

			
	----
	----
	CREATE TABLE #T1 (SUBDIV VARCHAR(254), link_face INT, link_pays INT, name_pays VARCHAR(254), code_pays VARCHAR(10), typ_oper TINYINT, link_inc int, name_vkr VARCHAR(254), code_ekr VARCHAR(10), summa NUMERIC(18,2), [hours] NUMERIC(18,2), [days] NUMERIC(18,2))

	INSERT INTO #T1	(SUBDIV, LINK_FACE, LINK_PAYS, NAME_PAYS, CODE_PAYS, TYP_OPER, link_inc, NAME_VKR, CODE_EKR, SUMMA, [HOURS], [DAYS])
	SELECT 
		s_j_c.NAME_SUBDIV AS SUBDIV, s_j_c.LINK_FACE, LINK_PAYS, NAME_PAYS, CODE_PAYS, TYP_OPER, link_inc, NAME_VKR, 
		CODE_EKR = CASE WHEN TYP_OPER = 3 THEN
							CASE WHEN @SALARY_PROV_OPT4 = 0 THEN 
									CASE WHEN ISNULL(s_j_c.CODE_EKR,'213') = '211' THEN '213' ELSE ISNULL(s_j_c.CODE_EKR,'213') END
								ELSE 
									CASE WHEN ISNULL(s_j_c.CODE_EKR,'213') IN ('211', '212') THEN '213' ELSE ISNULL(s_j_c.CODE_EKR,'213') END
							END
						ELSE s_j_c.CODE_EKR
					END, 
		SUMMA, [HOURS], [DAYS] 
	FROM 
		#s_j_c as s_j_c 
		inner join dbo.KS_OPTIONS_ZB zb on s_j_c.LINK_DEP = zb.ZB_LINK 
		LEFT JOIN DBO.SA_EMPLS_INFO(DEFAULT, DEFAULT) D ON s_j_c.LINK_EMPL = D.EMPL_LINK
	WHERE 
		period_begin between @varKSdDate1 and @varKSdDate2 
		and (LEN(@varKScVal1) <> 0 and s_j_c.LINK_VKR in (select LINK_VKR from #VKR) or LEN(@varKScVal1) = 0 )
		and (LEN(@varKScVal2) <> 0 and s_j_c.LINK_EKR in (Select link from #ekr) or LEN(@varKScVal2) = 0)
		and (LEN(@cVal3) = 0
			OR
				( s_j_c.SUBDIV_HEAD IN (select RECORD from dbo.OBJECT_VAR_SUBDIV_HEAD WHERE LINK_UP = @nOtborLink3)
				)
			)
 		AND (	--ОТБОР КАТЕГОРИЙ ДОЛЖНОСТЕЙ
			@CVAL4 <> '' AND ((s_j_c.LINK_KATEG <> 0 and  s_j_c.LINK_KATEG IN (SELECT RECORD FROM DBO.OBJECT_VAR_KATEG WHERE LINK_UP = @NOTBORLINK4))
								OR ( s_j_c.LINK_KATEG = 0 and  (select distinct st.KAT_LINK 
																from sa_item_move sm 
																	left join staff st on st.LINK_up = sm.STAFF_LINK and st.link = (SELECT MAX(link) from  staff where LINK_up = sm.STAFF_LINK)
																	left join SUBDIV su on su.link_up = st.SUBDIV_LINK and su.link = (SELECT MAX(link) from  SUBDIV where LINK_up = st.SUBDIV_LINK)
																where sm.EMPL_LINK = s_j_c.LINK_EMPL and sm.date_end >= @varKSdDate2
																) IN (SELECT RECORD FROM DBO.OBJECT_VAR_KATEG WHERE LINK_UP = @NOTBORLINK4)
									)
							  )
			
			OR
			@CVAL4 = '' )
		AND
			(@STATUS3 = 0 or @STATUS3 = 1 AND ISNULL(D.STATUS,0) <> 3)

	-- Проверка
	IF NOT EXISTS (SELECT * FROM #T1 WHERE typ_oper = 1)
		INSERT INTO #T1 (typ_oper) VALUES (1)
	IF NOT EXISTS (SELECT * FROM #T1 WHERE typ_oper = 2)
		INSERT INTO #T1 (typ_oper) VALUES (2)
	IF NOT EXISTS (SELECT * FROM #T1 WHERE typ_oper = 3)
		INSERT INTO #T1 (typ_oper) VALUES (3)

------------****************** Необлагаемые суммы по НДФЛ
;WITH 
	T1 AS 
	(
	SELECT DLINK = D.LINK, SK.LINK_EMPL, SUMMA = SUM(SK.SUMMA), SK.LINK_VKR, sf.code as code_vkr_N , SK.LINK_EKR , kg.code as code_ekr_n
	FROM
		dbo.SAL_DED_MONTH SK
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.REF_DEDUCT = SK.REF_DED
		Inner join  dbo.SAL_SFIN sf on sf.link = sk.link_vkr
		inner join dbo.kosgu  kg on kg.link = sk.link_ekr
	WHERE
		SK.DATE_DED BETWEEN @varKSdDate1 AND @varKSdDate2	
	GROUP BY
		D.LINK, SK.LINK_EMPL, SK.LINK_VKR, SK.LINK_EKR, sf.code	, kg.code
	),
	
	T2 AS 
	(
	SELECT 
		CJ.LINK_EMPL, DLINK = P.LINK_INC, CJ.LINK_VKR, CODE_VKR_n = CJ.NAME_VKR, CJ.LINK_EKR,  code_ekr_n = CJ.CODE_EKR, SUMMA = SUM(CJ.SUMMA)
	FROM
		#s_j_c CJ
		INNER JOIN dbo.PAYS P ON P.LINK = CJ.LINK_PAYS
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.LINK = P.LINK_INC
		inner join DICTIONARY_MROT_TABLE1 dm1 on  dm1.ref_pay = D.REF_DEDUCT 
		inner join DICTIONARY_MROT dm on dm.LINK = dm1.LINK_MINROT
	WHERE
		P.OBJECT = 1
		AND PERIOD_BEGIN BETWEEN @varKSdDate1 AND @varKSdDate2
		and dm.PERIOD between '20130101' AND '20131231'
		AND D.REF_DEDUCT IS NOT NULL
	GROUP BY
		CJ.LINK_EMPL, P.LINK_INC, CJ.LINK_VKR, CJ.LINK_EKR, CJ.NAME_VKR, CJ.CODE_EKR
	HAVING 
		SUM(CJ.SUMMA) <> 0	
	)	

	SELECT 
		PLINK = P.LINK, LINK_INC = P.LINK_INC, LINK_VKR= CJ.LINK_VKR,CODE_VKR_N = CJ.NAME_VKR, 
		LINK_EKR = CJ.LINK_EKR, CODE_EKR_N = CJ.CODE_EKR, SUM_NDFL = SUM(T1.SUMMA * CJ.SUMMA/T2.SUMMA)
	INTO #NO_NDFL_TMP
	FROM
		#s_j_c CJ
		INNER JOIN dbo.PAYS P ON P.LINK = CJ.LINK_PAYS
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.LINK = P.LINK_INC
		INNER JOIN T1 ON T1.LINK_EMPL = CJ.LINK_EMPL AND T1.DLINK = P.LINK_INC AND T1.LINK_VKR = CJ.LINK_VKR AND T1.LINK_EKR = CJ.LINK_EKR
		INNER JOIN T2 ON T2.LINK_EMPL = CJ.LINK_EMPL AND T2.DLINK = P.LINK_INC AND T2.LINK_VKR = CJ.LINK_VKR AND T2.LINK_EKR = CJ.LINK_EKR
	WHERE
		P.OBJECT = 1
		AND PERIOD_BEGIN BETWEEN @varKSdDate1 AND @varKSdDate2
		AND D.REF_DEDUCT IS NOT NULL
	GROUP BY
		P.LINK, P.LINK_INC, CJ.LINK_VKR, CJ.LINK_EKR, CJ.NAME_VKR, CJ.CODE_EKR
	ORDER BY  
		P.LINK, P.LINK_INC, CJ.LINK_VKR, CJ.LINK_EKR	


	SELECT PLINK,  LINK_VKR,CODE_VKR_N ,LINK_EKR , CODE_EKR_N, sum(Sum_NDFL) AS Sum_NDFL
	INTO #NO_NDFL
	FROM #NO_NDFL_TMP 
	GROUP BY PLINK, link_vkr , code_vkr_N, link_ekr,  code_ekr_n 

	DROP TABLE #NO_NDFL_tmp

	--- ************************** Не облагаемые суммы по Страховым взносам  
;WITH 
	T1 AS 
	(
	SELECT SE.LINK_EMPL, SUMMA = SUM(se.ded_m), SE.LINK_VKR  , sf.code as code_vkr_S, SE.LINK_EKR, kg.code as code_ekr_S
	from	dbo.SDOC_ESN_TABLE SE    
		  INNER JOIN 	pays p  ON p.link = se.LINK_PAY  AND p.way_calc = 6
		--INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.REF_DEDUCT = SK.REF_DED
		--inner join DICTIONARY_DEDUCT_SALARY_table dd on dd.LINK_TAX = se.link_pay
		
		INNER JOIN sdoc s on  s.link = SE.link_up 
		Inner join  dbo.SAL_SFIN sf on sf.link = SE.link_vkr
		inner join dbo.kosgu  kg on kg.link = SE.link_ekr
	WHERE isnull(se.ded_m,0) <> 0 
		and s.[OBJECT] = (SELECT link FROM s_objects WHERE code = 'DOCUMENTS_DEDUCT_ESN_G') 
		and s.[date] BETWEEN '20130101' AND '20131231'	
	GROUP BY
		 SE.LINK_EMPL, SE.LINK_VKR, SE.LINK_EKR, sf.code, kg.code	
	),

	T2 AS 
	(
	SELECT 
		/*PLINK= P.LINK,*/ CJ.LINK_EMPL/*, DLINK = P.LINK_INC*/, CJ.LINK_VKR, CODE_VKR_S = CJ.NAME_VKR, CJ.LINK_EKR, CODE_EKR_S = CJ.CODE_EKR , SUMMA = SUM(CJ.SUMMA)
	FROM #s_j_c  CJ
		INNER JOIN dbo.PAYS P ON P.LINK = CJ.LINK_PAYS
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.LINK = P.LINK_INC
		inner join DICTIONARY_MROT_TABLE2 dm2 on  dm2.ref_pay = D.REF_DEDUCT 
		inner join DICTIONARY_MROT dm on dm.LINK = dm2.LINK_MINROT
	WHERE
		P.OBJECT = 1
		AND PERIOD_BEGIN BETWEEN '20130101' AND '20131231'
		and dm.PERIOD between '20130101' AND '20131231'
		AND D.REF_DEDUCT IS NOT NULL
	GROUP BY
		 CJ.LINK_EMPL/*,P.LINK*/, P.LINK_INC, CJ.LINK_VKR, CJ.LINK_EKR,CJ.NAME_VKR,CJ.CODE_EKR
	HAVING 
		SUM(CJ.SUMMA) <> 0	
	)	

	SELECT 
		PLINK = P.LINK,LINK_VKR= CJ.LINK_VKR, LINK_EKR= CJ.LINK_EKR, CODE_VKR_S = CJ.NAME_VKR, CODE_EKR_S = CJ.CODE_EKR, SUM_STR= SUM(T1.SUMMA * CJ.SUMMA/T2.SUMMA)
	INTO #NO_STR
	FROM
		#s_j_c CJ
		INNER JOIN dbo.PAYS P ON P.LINK = CJ.LINK_PAYS
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.LINK = P.LINK_INC
		INNER JOIN T1 ON T1.LINK_EMPL = CJ.LINK_EMPL AND T1.LINK_VKR = CJ.LINK_VKR AND T1.LINK_EKR = CJ.LINK_EKR
		INNER JOIN T2 ON T2.LINK_EMPL = CJ.LINK_EMPL AND /*T2.DLINK = P.LINK_INC AND*/ T2.LINK_VKR = CJ.LINK_VKR AND T2.LINK_EKR = CJ.LINK_EKR
	WHERE
		P.OBJECT = 1
		AND PERIOD_BEGIN between '20130101' AND '20131231'
		AND D.REF_DEDUCT IS NOT NULL
	GROUP BY
		P.LINK, CJ.LINK_VKR, CJ.LINK_EKR,CJ.NAME_VKR, CJ.CODE_EKR
	ORDER BY  
		P.LINK, CJ.LINK_VKR, CJ.LINK_EKR	

--*************************************************


	-- Удаление временной таблицы #s_j_c
	DROP TABLE #s_j_c

	----
	IF LEN(@CVAL4) <> 0 BEGIN

		set @varKScOtbor4 = 'Отбор Категорий: '

		select distinct RECORD INTO #T2 FROM dbo.OBJECT_VAR_KATEG WHERE LINK_UP = @NOTBORLINK4

		update A set @varKScOtbor4 = @varKScOtbor4 + ltrim(rtrim(B.NAME)) + ','
		from #T2 A inner join dbo.KATEG B on A.RECORD = B.LINK

		set @varKScOtbor4 = left(@varKScOtbor4,len(@varKScOtbor4)-1)
	END

	if not exists (Select typ_oper from #T1 where typ_oper = 1)
		insert into #T1 (SUBDIV, link_face, link_pays, name_pays, code_pays, typ_oper, name_vkr, code_ekr, summa, hours, days) values ('', 0,0,'','',1,'','',0,0,0)
	if not exists (Select typ_oper from #T1 where typ_oper = 2)
		insert into #T1 (SUBDIV, link_face, link_pays, name_pays, code_pays, typ_oper, name_vkr, code_ekr, summa, hours, days) values ('', 0,0,'','',2,'','',0,0,0)
	if not exists (Select typ_oper from #T1 where typ_oper = 3)
		insert into #T1 (SUBDIV, link_face, link_pays, name_pays, code_pays, typ_oper, name_vkr, code_ekr, summa, hours, days) values ('', 0,0,'','',3,'','',0,0,0)
	
	----
	IF LEN(@CVAL3) <> 0 BEGIN
		set @varKScOtbor3 = 'Отбор Подразделений: '
		update A set @varKScOtbor3 = @varKScOtbor3 + ltrim(rtrim(B.NAME)) + ','
		from dbo.OBJECT_VAR_SUBDIV_HEAD A inner join dbo.subdiv B on A.RECORD = B.LINK_UP
		where A.LINK_UP = @nOtborLink3

		set @varKScOtbor3 = left(@varKScOtbor3,len(@varKScOtbor3)-1)
	END

	----	
	set @varKSCountEmpl = (select count(link_face) from (select distinct link_face from #T1)T2)
	set @varKSPeriodStr = ''+ rtrim(convert(varchar(10),@varKSdDate1,104))+' - ' + rtrim(convert(varchar(10),@varKSdDate2,104))

	select 	[count] =  ltrim(rtrim(convert(varchar(10), coalesce(@varKSCountEmpl,0)))),
			[PERIOD] = coalesce(@varKSPeriodStr,''),
			[OTBOR] = ltrim(rtrim(coalesce(@varKScOtbor,''))),
			[OTBOR2] = coalesce(@varKScOtbor2,''),
			[OTBOR3] = coalesce(@varKScOtbor3,''),
			[OTBOR4] = coalesce(@varKScOtbor4,''),
			[OTBOR5] = (case when @status3 = 1 then 'Без учёта внешних совместителей' else '' end)


	DECLARE @Script varchar(8000)

	SET @Script = 
	'	
	select
		[typ_name] =  + (case when typ_oper = 1 then ''Начислено'' when typ_oper = 2 then ''Удержано'' else ''Отчислено'' end),
		* 
	from 
	(select
		' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV' ELSE '''''' END + ' AS SUBDIV,
		link_pays,
		name_pays,
		code_pays, 
		typ_oper, 
		name_vkr ' + case when coalesce(@detailed_SFIN,0) = 1 then '' else '=''Все''' end + ', 
		code_ekr ' + case when coalesce(@detailed_EKR,0) = 1 then '' else '=''Все''' end + ', 
		sum(summa) as summa,sum(hours) as hours, sum(days) as days,
		nn.sum_nDFL as sum_nDFL,
		ns.sum_STR as sum_STR
	from #T1 t
	left join  #NO_NDFL nn on nn.PLINK = t.link_pays and nn.code_vkr_n = t.name_vkr and   nn.code_ekr_n = t.code_ekr
	left join  #NO_STR ns on ns.PLINK = t.link_pays and ns.code_vkr_s = t.name_vkr and   ns.code_ekr_s = t.code_ekr
	where typ_oper = 1
	group by ' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV,' ELSE '' END + ' link_pays, typ_oper,name_pays,code_pays ' 
	+ case when coalesce(@detailed_SFIN,0) = 1 then ',t.name_vkr, nn.code_vkr_n, ns.code_vkr_s' else '' end  
	+ case when coalesce(@detailed_EKR,0) = 1 then ',t.code_ekr, nn.code_ekr_n, ns.code_ekr_s'  else '' end + ' , nn.sum_ndfl, ns.sum_STR
	) T2
	 order by ' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV,' ELSE '' END + 'typ_oper,code_pays' + case when coalesce(@detailed_SFIN,0) = 1 then ',name_vkr' else '' end + case when coalesce(@detailed_EKR,0) = 1 then ',code_ekr' else '' end

exec( @Script)



	SET @Script = 
	'	
	select
		[typ_name] =  + (case when typ_oper = 1 then ''Начислено'' when typ_oper = 2 then ''Удержано'' else ''Отчислено'' end),
		* 
	from 
	(select
		' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV' ELSE '''''' END + ' AS SUBDIV,
		link_pays,
		name_pays,
		code_pays, 
		typ_oper, 
		name_vkr ' + case when coalesce(@detailed_SFIN,0) = 1 then '' else '=''Все''' end + ', 
		code_ekr ' + case when coalesce(@detailed_EKR,0) = 1 then '' else '=''Все''' end + ', 
		sum(summa) as summa,sum(hours) as hours, sum(days) as days
	from #T1
	where typ_oper = 2
	group by ' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV,' ELSE '' END + ' link_pays, typ_oper,name_pays,code_pays ' 
	+ case when coalesce(@detailed_SFIN,0) = 1 then ',name_vkr' else '' end  
	+ case when coalesce(@detailed_EKR,0) = 1 then ',code_ekr' else '' end + '
	) T2
	 order by ' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV,' ELSE '' END + 'typ_oper,code_pays' + case when coalesce(@detailed_SFIN,0) = 1 then ',name_vkr' else '' end + case when coalesce(@detailed_EKR,0) = 1 then ',code_ekr' else '' end

	exec( @Script)

	SET @Script = 
	'	
	select
		[typ_name] =  + (case when typ_oper = 1 then ''Начислено'' when typ_oper = 2 then ''Удержано'' else ''Отчислено'' end),
		* 
	from 
	(select 
		' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV' ELSE '''''' END + ' AS SUBDIV,
		link_pays,
		name_pays,
		code_pays, 
		typ_oper, 
		name_vkr ' + case when coalesce(@detailed_SFIN,0) = 1 then '' else '=''Все''' end + ', 
		code_ekr ' + case when coalesce(@detailed_EKR,0) = 1 then '' else '=''Все''' end + ', 
		sum(summa) as summa,sum(hours) as hours, sum(days) as days
	from #T1
	where typ_oper = 3
	group by ' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV,' ELSE '' END + ' link_pays, typ_oper,name_pays,code_pays ' 
	+ case when coalesce(@detailed_SFIN,0) = 1 then ',name_vkr' else '' end  
	+ case when coalesce(@detailed_EKR,0) = 1 then ',code_ekr' else '' end + '
	) T2
	 order by ' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV,' ELSE '' END + 'typ_oper,code_pays' + case when coalesce(@detailed_SFIN,0) = 1 then ',name_vkr' else '' end + case when coalesce(@detailed_EKR,0) = 1 then ',code_ekr' else '' end

	exec( @Script)



	IF coalesce(@detailed_SFIN,0) = 1 and coalesce(@detailed_EKR,0) = 1
		SELECT 'Итого по группе' as TITLE,
			typ_oper, name_vkr, code_ekr, summa = sum(summa), sum_nDFL , sum_STR
		FROM #T1 t 
		left join (SELECT code_vkr_n , code_ekr_n, sum_nDFL = sum(sum_nDFL) from  #NO_NDFL  GROUP BY code_vkr_n , code_ekr_n) n on n.code_vkr_n = t.name_vkr and   n.code_ekr_n = t.code_ekr and typ_oper = 1
		left join  (SELECT code_vkr_s , code_ekr_s, sum_STR = sum(sum_STR) from  #NO_STR  GROUP BY code_vkr_s , code_ekr_s) s on s.code_vkr_s = t.name_vkr and   s.code_ekr_s = t.code_ekr and typ_oper = 1
		GROUP BY t.typ_oper, t.name_vkr, code_ekr, sum_nDFL , sum_STR
		ORDER BY typ_oper, name_vkr, code_ekr

	IF coalesce(@detailed_SFIN,0) = 1 and coalesce(@detailed_EKR,0) = 0
		SELECT 'Итого по группе' as TITLE,
			typ_oper, name_vkr, code_ekr = '', summa = sum(summa) , sum_nDFL , sum_STR
		FROM #T1 t 
		left join (SELECT code_vkr_n , sum_nDFL = sum(sum_nDFL) from  #NO_NDFL  GROUP BY code_vkr_n ) n on n.code_vkr_n = t.name_vkr  and typ_oper = 1
		left join  (SELECT code_vkr_s , sum_STR = sum(sum_STR) from  #NO_STR  GROUP BY code_vkr_s ) s on s.code_vkr_s = t.name_vkr  and typ_oper = 1
		GROUP BY t.typ_oper, t.name_vkr,sum_nDFL, sum_STR
		ORDER BY typ_oper, name_vkr


	IF coalesce(@detailed_SFIN,0) = 0 and coalesce(@detailed_EKR,0) = 1
		SELECT 'Итого по группе' as TITLE,
			typ_oper, name_vkr = '', code_ekr, summa = sum(summa),sum_nDFL, sum_STR
		FROM #T1 t 
		left join (SELECT code_ekr_n , sum_nDFL = sum(sum_nDFL) from  #NO_NDFL  GROUP BY code_ekr_n ) n on n.code_ekr_n = t.code_ekr  and typ_oper = 1
		left join  (SELECT code_ekr_s , sum_STR = sum(sum_STR) from  #NO_STR  GROUP BY code_ekr_s ) s on s.code_ekr_s = t.code_ekr  and typ_oper = 1
		GROUP BY typ_oper, code_ekr, sum_nDFL, sum_STR
		ORDER BY typ_oper, code_ekr


DROP TABLE #NO_NDFL
DROP TABLE #NO_STR

	IF coalesce(@detailed_SFIN,0) = 0 and coalesce(@detailed_EKR,0) = 0
		SELECT DISTINCT '' as TITLE, typ_oper, name_vkr = '', code_ekr = '', summa = 0,sum_nDFL = 0, sum_STR = 0 FROM #T1 GROUP BY typ_oper 

end




GO


GRANT EXECUTE ON dbo.[SD_REP_SVOD] TO PUBLIC

GO




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

GO

CREATE          PROCEDURE dbo.FB_BUDG_SMETA_REPORT
		@dDate		 datetime,
		@iDocType	 tinyint,
		--@iDopEkr	 tinyint,
		@cVal1		 char(1), 
		@nOtborLink1 int,
		@cVal2		 char(1) = '', 
		@nOtborLink2 int,
		@cVal3		 char(1) = '', 
		@nOtborLink3 int
			

AS
DECLARE		@cCROSS_TABLE 	char(100),
			@cSQL_STR		VARCHAR (8000),
			@cSQL_STRU		VARCHAR (8000),
			@iAccount		int,
			@dDateBegP		datetime,
			@varKSiOwnDep	int,
			@cYear			char(4),
			@iMonthCount	tinyint,
			@iMonth			tinyint
		


-- Выбираем КБК из фильтров по Подразделам и ЦС
DECLARE @tVKR  TABLE (LINK [INT])	
DECLARE @tSGU  TABLE (LINK [INT])	
DECLARE @tDCL  TABLE (LINK [INT])	

IF LEN (@cVal1) > 0
	INSERT INTO @tVKR
	SELECT RECORD
	FROM dbo.OBJECT_VAR_KBK
	where LINK_UP = @nOtborLink1

IF LEN (@cVal2) > 0
	INSERT INTO @tSGU
	SELECT RECORD
	FROM dbo.OBJECT_VAR_KOSGU 
	where LINK_UP = @nOtborLink2

IF LEN (@cVal3) > 0
	INSERT INTO @tDCL
	SELECT RECORD
	FROM dbo.OBJECT_VAR_DOP_CLASSIF 
	where LINK_UP = @nOtborLink3

set @dDateBegP = dbo.DateBeginOfYear(@dDate)
select @iAccount = LINK 
from dbo.S_ACCOUNTS
where CODE = '1.501.13' 

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

CREATE TABLE #TAB_TEMPI (
	PER_NUM		int,
	VKR			int, 
	EKR			INT, 
	SUMMA	[numeric](28, 2) NULL)

CREATE TABLE #TAB_TEMP (
	VKR			int, 
	EKR			INT, 
	SUMMA	[numeric](28, 2) NULL)


insert into #TAB_TEMP
select  L.KBK,
		L.EKR,
		sum(isnull(k_summa,0))
from dbo.FB_LimitOborotByPeriod(@dDateBegP,@dDate, @iAccount) L
where  L.DEP_LINK = @varKSiOwnDep and 
		exists(select * from dbo.FINANSE_HEAD where LINK = L.LINK_UP and (PARAM & 0x1) = 0) and 
		(@cVal1 = '' or @cVal1 <> '' and L.KBK in (select LINK from @tVKR)) and
		(@cVal2 = '' or @cVal2 <> '' and L.SGU in (select LINK from @tSGU)) and
		(@cVal3 = '' or @cVal3 <> '' and L.AP2 in (select LINK from @tDCL)) and 
		@iDocType < 3
GROUP BY L.KBK,L.EKR
HAVING sum(isnull(k_summa,0)) <> 0


insert into #TAB_TEMPI
select  month(L.DATE_PROV),
		L.KBK,
		L.EKR,
		sum(isnull(k_summa,0))
from dbo.FB_LimitOborotByPeriod(@dDateBegP,@dDate, @iAccount) L
where  L.DEP_LINK = @varKSiOwnDep and 
		exists(select * from dbo.FINANSE_HEAD where LINK = L.LINK_UP and (PARAM & 0x1) = 1)  and 
		(@cVal1 = '' or @cVal1 <> '' and L.KBK in (select LINK from @tVKR)) and
		(@cVal2 = '' or @cVal2 <> '' and L.SGU in (select LINK from @tSGU))and
		(@cVal3 = '' or @cVal3 <> '' and L.AP2 in (select LINK from @tDCL))
GROUP BY L.KBK,L.EKR, month(L.DATE_PROV)
HAVING sum(isnull(k_summa,0)) <> 0

	

if @iDocType > 1
begin
	select @iMonthCount = count(*) 
	from (select PER_NUM
			from #TAB_TEMPI
			group by PER_NUM) A
	if @iMonthCount = 0
	begin 
		select 0 where 0>1
		return 0
	end
			
	set @cSQL_STR = '
	if object_id(''tempdb..##TAB_TEMP_R'') is NOT NULL drop table ##TAB_TEMP_R 
	CREATE TABLE ##TAB_TEMP_R (
	VKR		int,
	EKR		int'

	set @cSQL_STRU = '
	update ##TAB_TEMP_R set '


	set @iMonth = 1
	WHILE @iMonth <= @iMonthCount 
	BEGIN
		set @cSQL_STR = @cSQL_STR + ',
	PER_NUM_' + ltrim(rtrim(str(@iMonth))) + '			int,
	SUMMA_' + ltrim(rtrim(str(@iMonth))) + '		NUMERIC (28,4)'
		set @cSQL_STRU = @cSQL_STRU + '
		PER_NUM_' + ltrim(rtrim(str(@iMonth))) + 
		' = (select top 1 PER_NUM_' + ltrim(rtrim(str(@iMonth))) + ' from ##TAB_TEMP_R where PER_NUM_' + ltrim(rtrim(str(@iMonth))) + ' is not null),'
		set @iMonth = @iMonth + 1
	END

	set @cSQL_STR = @cSQL_STR + ',
	SUMMA		NUMERIC (28,4),
	SUMMAI		NUMERIC (28,4),
	VKR_CODE	VARCHAR(30),
	EKR_CODE	char(3),
	NAME		VARCHAR(254),
	DIV_CODE	VARCHAR(4),
	DIV_NAME	VARCHAR(254),
	VKR_NAME	VARCHAR(254),
	YEAR  		CHAR(4))'
	
	
	set @cSQL_STRU = left(@cSQL_STRU,len(@cSQL_STRU)- 1)
	
	EXEC (@cSQL_STR)

	-- Разворачиваем таблицу по месяцам
	EXEC X_GET_TABLE_NAME @cCROSS_TABLE OUTPUT
	EXEC M_CROSS_TABLE 'VKR, EKR', 'PER_NUM', 'INT', 'SUMMA', 'NUMERIC (28,4)', 'SUM (SUMMA) AS SUMMA', '#TAB_TEMPI', @cCROSS_TABLE
	
	set @cSQL_STR = '
	insert into ##TAB_TEMP_R
	select T.*,
			SUMMA = isnull(TS.SUMMA,0),
			SUMMAI = isnull(TI.SUMMA,0) + isnull(TS.SUMMA,0),
			VKR_CODE = KBK.CODE,
			EKR_CODE = isnull(SGU.CODE,''''),
			NAME = 	coalesce(SGU.NAME,KBK.NAME),
			KBK.DIV_CODE,
			KBK.DIV_NAME,
			VKR_NAME = KBK.NAME,
			YEAR = ' + ltrim(str(year(@dDate))) + '
	from (select VKR, EKR from #TAB_TEMP union
		  select VKR, EKR from #TAB_TEMPI) C
	LEFT JOIN ' + rtrim(@cCROSS_TABLE) + ' T ON T.VKR = C.VKR and T.EKR = C.EKR 
	LEFT JOIN dbo.BI_DICTION_KBK_FULL KBK ON C.VKR = KBK.LINK
	LEFT JOIN dbo.KOSGU SGU ON C.EKR = SGU.LINK
	LEFT JOIN (select VKR, EKR, sum(SUMMA) as SUMMA from #TAB_TEMPI GROUP BY VKR, EKR) TI ON TI.VKR = C.VKR and TI.EKR = C.EKR
	LEFT JOIN (select VKR, EKR, sum(SUMMA) as SUMMA from #TAB_TEMP GROUP BY VKR, EKR) TS ON TS.VKR = C.VKR and TS.EKR = C.EKR
	'
	EXEC (@cSQL_STR)
	
	EXEC ('DROP TABLE ' + @cCROSS_TABLE)
	
	EXEC (@cSQL_STRU)
	print @cSQL_STRU
	
	EXEC ('select * from ##TAB_TEMP_R ORDER BY DIV_CODE, VKR_CODE, EKR_CODE')
	EXEC ('DROP TABLE ##TAB_TEMP_R')


end
else
	select T.*,
			VKR_CODE = KBK.CODE,
			EKR_CODE = isnull(SGU.CODE,''''),
			NAME = 	coalesce(SGU.NAME,KBK.NAME),
			KBK.DIV_LINK,
			KBK.DIV_NAME,
			VKR_NAME = KBK.NAME,
			YEAR = ltrim(str(year(@dDate)))
	from #TAB_TEMP T 
	LEFT JOIN dbo.BI_DICTION_KBK_FULL KBK ON T.VKR = KBK.LINK
	LEFT JOIN dbo.KOSGU SGU ON T.EKR = SGU.LINK
	ORDER BY KBK.CODE,isnull(SGU.CODE,'')
DROP TABLE #TAB_TEMP
DROP TABLE #TAB_TEMPI


RETURN 1




GO


GRANT EXECUTE ON dbo.[FB_BUDG_SMETA_REPORT] 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(4),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_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)

	/*заявленные имущественные вычеты*/  -- DED_TYPE = 1 - имущественные, 2-  социальные
	CREATE TABLE #td (LINK_PERSON INT ,NUM_REF VARCHAR(15),DATE_REF DATETIME,IFNS_CODE VARCHAR(20),DED_TYPE TINYINT)
	INSERT INTO #td (LINK_PERSON ,NUM_REF,DATE_REF,IFNS_CODE,DED_TYPE)
	Select LINK_PERSON, 
		   NUM_REF, 
		   DATE_REF, 
		   IFNS_CODE,
		   DED_TYPE = 1 
	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 AND TD1.LINK_DICTION IN (SELECT  LINK FROM DICTIONARY_TYP_DEDUCTION  WHERE NUMBER ='4')  )
	UNION SELECT 
		   LINK_PERSON, 
		   NUM_REF, 
		   DATE_REF, 
		   IFNS_CODE,
		   DED_TYPE = 2 
	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 AND TD1.LINK_DICTION IN (SELECT  LINK FROM DICTIONARY_TYP_DEDUCTION  WHERE NUMBER IN('11','12','13')) )


	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 = td1.NUM_REF , -- на имущественные вычеты
		ddoc_td = td1.DATE_REF,
		ifnsdoc_td = td1.ifns_code,
		nDoc_SD = td2.NUM_REF, -- на социальные вычеты 
		dDoc_SD = td2.DATE_REF,
		ifnsdoc_sd = td2.ifns_code,
		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,
		td1.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 OUTER JOIN   #td td1 on R.LINK_FACE = td1.LINK_PERSON AND td1.DED_TYPE = 1 /*имущественные вычеты*/
		LEFT OUTER JOIN   #td td2 on R.LINK_FACE = td2.LINK_PERSON AND td2.DED_TYPE = 2 /*социальные вычеты*/
	--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.[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(30),  @varKSparSFIN_OLD varchar(30) , @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)

---Расширить период редактирования
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)		
	
	/* ШТАТНОЕ РАСПИСАНИЕ */
	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
		
	INTO	#TMP
	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
		)
		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
		from #TMP

	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

	--Замена в договорах
	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

	--в постоянных удержаниях тоже замена КБК
	--новые строки со старыми линками
	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



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


/*выбор последних линков сотрудников для статусов основной и внешний совместитель
берется последний табельный, если увольнялся, затем заново принимался*/
	
IF OBJECT_ID('TEMPDB..#EMPLS1','U') IS NOT NULL
DROP TABLE #EMPLS1

CREATE TABLE #EMPLS1 (DEP_LINK INT, PERS_LINK INT, LINK INT, TAB VARCHAR(254), NUM INT, LINK_EMPL2 INT)

INSERT INTO #EMPLS1 (DEP_LINK, PERS_LINK, LINK, TAB, NUM)
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))
		--AND PERS_LINK = 17896

UPDATE A SET A.LINK_EMPL2 = B.LINK
FROM #EMPLS1 A INNER JOIN #EMPLS1 B ON A.DEP_LINK = B.DEP_LINK AND A.PERS_LINK = B.PERS_LINK
WHERE B.NUM = 1
		
/*выбор линков сотрудников для статусов внутренний совместитель*/

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

CREATE TABLE #EMPLS2 (DEP_LINK INT, PERS_LINK INT, LINK INT, TAB VARCHAR(254), NUM INT, LINK_EMPL2 INT)

INSERT INTO #EMPLS2 (DEP_LINK, PERS_LINK, LINK, TAB, NUM)
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))
		--AND PERS_LINK = 17896

UPDATE A SET A.LINK_EMPL2 = B.LINK
FROM #EMPLS2 A INNER JOIN #EMPLS2 B ON A.DEP_LINK = B.DEP_LINK AND A.PERS_LINK = B.PERS_LINK
WHERE B.NUM = 1

SELECT 
	T.LINK,
	T.LINK_EMPL,
	T.TAB_NUM,
	T.[NAME_EMPL], 
	T.[STATUS],
	T.NUM_STAKE,	
	LINK_VKR = ISNULL(SF.LINK_SS_SFIN, T.LINK_VKR),
	NAME_VKR = ISNULL(SF2.CODE, T.NAME_VKR),
	T.LINK_EKR,
	T.CODE_EKR,
	LINK_VKR2 = T.LINK_VKR,
	NAME_VKR2 = T.NAME_VKR
FROM
(			
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 DEP_LINK, LINK, LINK_EMPL2 FROM #EMPLS1
		/*выбор линков сотрудников для статусов внутренний совместитель*/
		UNION
		SELECT DEP_LINK, LINK, LINK_EMPL2 FROM #EMPLS2
			) T ON T.DEP_LINK = E.DEP_LINK AND T.LINK_EMPL2 = E.LINK
	INNER JOIN dbo.CALCULATE_JURNAL JC ON JC.LINK_EMPL = T.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
	EXISTS ( SELECT * FROM dbo.TAX_REF TR INNER JOIN dbo.PAYS P1 ON P1.LINK = TR.LINK_TAX WHERE P1.[OBJECT] = 3 AND TR.LINK_PAYS = JC.LINK_PAYS)
	AND
	E.DEP_LINK = @DEP_LINK
	AND
	PS.[OBJECT] = 1
	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)
) T
INNER JOIN dbo.SAL_SFIN SF ON SF.LINK = T.LINK_VKR
LEFT JOIN dbo.SAL_SFIN SF2 ON SF2.LINK = SF.LINK_SS_SFIN
	
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.[RJ_AUTOFILL_2GS_GZ_2016]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RJ_AUTOFILL_2GS_GZ_2016]

GO

/*
© Кейсистемс (Keysystems), 2008 
*/
CREATE PROCEDURE dbo.[RJ_AUTOFILL_2GS_GZ_2016]
	@varKSsFLink	int			-- экземпляр формы, для которой используется автозаполнение
AS
--//--

declare @link_form int
declare @date_begin datetime			-- дата формирования
declare @link_table int				-- ссылка на талицу
declare @link_col int				-- ссылка на колонку
declare @link_row int				-- ссылка на строку
--
--перенос формы из архивной базы
exec RN_MOVE_FORM_FROM_ARH @varKSsFLink


delete from report_summa where link_saved_form = @varKSsFLink
--
select @link_form = link_form, @date_begin = dbo.DateEndOfMonth(begin_date) from report_saved_forms where link_saved_form = @varKSsFLink
-----------------------------------
-- таблица всех сотрудников
select	[LINK] = 	 EM_PL.LINK,							-- ССЫЛКА НА СОТРУДНИКА
	[PERS_LINK] = 	 EM_PL.PERS_LINK,						-- ССЫЛКА НА ФИЗИЧЕСКОЕ ЛИЦО
	[GOSSL] = 	 ST.GOSSL,							-- ТИП ДОЛЖНОСТИ (1- ГОС., 2- ГОС.ГРАЖД.)
	[KAT_GOS_CODE] = ST.kat_gos_CODE,						-- КАТЕГОРИЯ ДОЛЖНОСТИ (1- рук, 2- помощ, 3- спец, 4- об.спец)
	[GR_GOS_CODE] =  ST.gr_gos_CODE,						-- ГРУППА ДОЛЖНОСТИ (1- высш, 2- глав, 3- вед, 4-с тар, 5- млад)
	[SEX] = 	 P.SEX,								-- ПОЛ (1- муж, 2- жен)
	-- ДАННЫЕ ДЛЯ УСЛОВИЙ ВЫБОРКИ СОТРУДНИКОВ
	[NOTWORK] =	EM_PL.NOTWORK,
	[NEW_FACE] =	IM.NEW_FACE,
	[TYPE_MOVE] = 	IM.TYPE,
	[TEMP_LINK] =	IM.TEMP_LINK,
	[DATE_END2] = 	IM.DATE_END2
into	#EMPLS_INFO
from	KU_EMPL_PLACING_FN(@date_begin) EM_PL left join DICTIONARY_STAFF_FN(@date_begin) ST
	on EM_PL.STAFF_LINK = ST.STAFF_LINK LEFT JOIN PERSON P
	on EM_PL.PERS_LINK = P.LINK LEFT JOIN ITEM_MOVE IM
	on EM_PL.ITEM_MOVE_LINK = IM.LINK
where	EM_PL.dep_link = (select dep_link from USER_DEP)				-- СОТРУДНИКИ ТОЛЬКО ТЕКУЩЕЙ ОРГАНИЗАЦИИ
	and EM_PL.sack = 0								-- ТОЛЬКО РАБОТАЮЩИЕ (ИСКЛЮЧАЕМ УВОЛЕННЫХ)
	and isnull(EM_PL.DATE_BEGIN,0) != 0						-- ГАРАНТИРОВАННО ПРИНЯТЫХ (ИСКЛЮЧАЕМ ТЕХ, КТО ВИСИТ В ПРОЕКТАХ ПРИКАЗАХ)
	and ST.GOSSL in (1,2)

DELETE FROM #EMPLS_INFO WHERE ISNULL(KAT_GOS_CODE,0) = 0 OR ISNULL(GR_GOS_CODE,0) = 0

DECLARE	@SQL_STR VARCHAR(2000)
DECLARE @OPT INT
	SET @OPT = dbo.sa_get_option_by_code('KADRY_OPT4')
	SET @SQL_STR =	CASE WHEN @OPT = 2 THEN							-- ИСКЛЮЧАЕМ ВРЕМЕННЫХ СОТРУДНКИОВ
			'
			DELETE	FROM #EMPLS_INFO 					
			WHERE	NOTWORK = 1
			'
		     WHEN @OPT = 1 THEN							-- ИСКЛЮЧАЕМ ВРЕМЕННО НЕ РАБОТЮЩИХ ОСНОВНЫХ СОТРУДНИКОВ
			'
			DELETE	FROM #EMPLS_INFO
			WHERE	(NEW_FACE = 1 AND ISNULL(TEMP_LINK,0) != 0)					-- если временно приняты вместо кого-то
				OR (NEW_FACE = 1 AND ISNULL(DATE_END2,''99991231'') != ''99991231'') 		-- если просто приняты временнно
				OR (NEW_FACE = 0 AND TYPE_MOVE = 1)						-- если перведены временно
			'	
		END
EXEC(@SQL_STR)

-----------------------------------
-- таблица всех курсов повышений квалификаций в отчетном году
SELECT	[EMPL] = 	EI.EMPL_LINK,				-- ссылка на сотрудника
	[DATE] = 	EI.DATE_END,				-- дата окончания
	[DIR] = 	EI.DIRECTION,				-- направление
								--		1) урпавленческое
								--		2) правовое
								--		3) организационно-экономическое
								--		4) планово-финансовое
								--		5) информационно-аналитическое
								--		6) другое
	[TIME] = 	EI.TIME,				-- количество часов
	[FORM] = 	EI.FORM_EDUC,				-- форма обучения
								--		1) с отрывом от службы
								--		2) без отрыва от службы
								--		3) частично
	[GOS] = 	CASE WHEN S.GOS_FLAG = 1 THEN 1		-- тип вуза
			     ELSE 2				--		1) государственный
			END,					--		2) негосударственный
	[FIN] = 	EI.FIN_SOURCE				-- источник финансирования обучения
								--		1) федеральный бюджет
								--		2) федеральный бюджет (гос.закакз)
								--		3) бюджет субъекта РФ
								--		4) бюджет субъекта РФ (гос.заказ)
								--		5) муниципальный бюджет
								--		6) муниципальный бюджет (мун.заказ)
								--		7) средства международных органов и организаций
								--		8) средства самого служащего
								--		9) иные источники финансирования
INTO	#EMPL_INCQUAL
FROM	EMPL_INCQUAL EI LEFT JOIN SCHOOL S ON EI.SCHOOL_LINK = S.LINK
WHERE	YEAR(EI.DATE_END) = YEAR(@date_begin)			-- ТОЛЬКО ПРОШЕДШИЕ ЗА ТЕКУЩИЙ ГОД
	AND EI.DATE_END <= @date_begin				-- ТОЛЬКО ПРОШЕДШИЕ ДО ТЕКУЩЕЙ ДАТЫ
	AND EI.TIME >= 72

-----------------------------------
-- таблица всех профессиональных переподготовок в отчетном году
SELECT	[EMPL] = 	EP.EMPL_LINK,				-- ссылка на сотрудника
	[DATE] = 	EP.DATE_END,				-- дата окончания
	[DIR] = 	EP.DIRECTION,				-- направление
								--		1) урпавленческое
								--		2) правовое
								--		3) организационно-экономическое
								--		4) планово-финансовое
								--		5) информационно-аналитическое
								--		6) другое
	[TIME] = 	EP.TIME,				-- количество часов
	[FORM] = 	EP.FORM_EDUC,				-- форма обучения
								--		1) с отрывом от службы
								--		2) без отрыва от службы
								--		3) частично
	[GOS] = 	S.GOS_FLAG,				-- тип вуза
								--		1) государственный
								--		2) негосударственный
	[FIN] = 	EP.FIN_SOURCE				-- источник финансирования обучения
								--		1) федеральный бюджет
								--		2) федеральный бюджет (гос.закакз)
								--		3) бюджет субъекта РФ
								--		4) бюджет субъекта РФ (гос.заказ)
								--		5) муниципальный бюджет
								--		6) муниципальный бюджет (мун.заказ)
								--		7) средства международных органов и организаций
								--		8) средства самого служащего
								--		9) иные источники финансирования
INTO	#EMPL_PROFP
FROM	EMPL_PROFP EP LEFT JOIN SCHOOL S ON EP.SCHOOL_LINK = S.LINK
WHERE	YEAR(EP.DATE_END) = YEAR(@date_begin)			-- ТОЛЬКО ПРОШЕДШИЕ ЗА ТЕКУЩИЙ ГОД
	AND EP.DATE_END <= @date_begin				-- ТОЛЬКО ПРОШЕДШИЕ ДО ТЕКУЩЕЙ ДАТЫ

--*******************************--
--********** РАЗДЕЛ 1 ***********--
--*******************************--
-- выбор таблицы
select @link_table = link_table from report_tables where link_form = @link_form and orders = 1
-- заполнение данных
-- **************************************************************
-- ***********************   3 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 3
-- 101
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 2)
-- 104
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '1' and GR_GOS_CODE = '1')
-- 105
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '1' and GR_GOS_CODE = '2')
-- 106
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '1' and GR_GOS_CODE = '3')
-- 107
select @link_row = link_row from report_rows where link_table = @link_table and orders = 8
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '2' and GR_GOS_CODE = '1')
-- 109
select @link_row = link_row from report_rows where link_table = @link_table and orders = 9
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '2' and GR_GOS_CODE = '2')
-- 110
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '2' and GR_GOS_CODE = '3')
-- 112
select @link_row = link_row from report_rows where link_table = @link_table and orders = 12
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '3' and GR_GOS_CODE = '1')
-- 113
select @link_row = link_row from report_rows where link_table = @link_table and orders = 13
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '3' and GR_GOS_CODE = '2')
-- 114
select @link_row = link_row from report_rows where link_table = @link_table and orders = 14
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '3' and GR_GOS_CODE = '3')
-- 115
select @link_row = link_row from report_rows where link_table = @link_table and orders = 15
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '3' and GR_GOS_CODE = '4')
-- 117
select @link_row = link_row from report_rows where link_table = @link_table and orders = 17
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '4' and GR_GOS_CODE = '2')
-- 118
select @link_row = link_row from report_rows where link_table = @link_table and orders = 18
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '4' and GR_GOS_CODE = '3')
-- 119
select @link_row = link_row from report_rows where link_table = @link_table and orders = 19
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '4' and GR_GOS_CODE = '4')
-- 120
select @link_row = link_row from report_rows where link_table = @link_table and orders = 20
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 1 and KAT_GOS_CODE = '4' and GR_GOS_CODE = '5')
-- 122
select @link_row = link_row from report_rows where link_table = @link_table and orders = 22
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where SEX = 2)
-- 123
select @link_row = link_row from report_rows where link_table = @link_table and orders = 23
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where SEX = 1)
-- **************************************************************
-- ***********************   5 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 5
-- 101
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 2 AND ISNULL(EP.EMPL,0) != 0)
-- 104
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '1' AND ISNULL(EP.EMPL,0) != 0)
-- 105
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '2' AND ISNULL(EP.EMPL,0) != 0)
-- 106
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '3' AND ISNULL(EP.EMPL,0) != 0)
-- 108
select @link_row = link_row from report_rows where link_table = @link_table and orders = 8
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '1' AND ISNULL(EP.EMPL,0) != 0)
-- 109
select @link_row = link_row from report_rows where link_table = @link_table and orders = 9
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '2' AND ISNULL(EP.EMPL,0) != 0)
-- 110
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '3' AND ISNULL(EP.EMPL,0) != 0)
-- 112
select @link_row = link_row from report_rows where link_table = @link_table and orders = 12
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '1' AND ISNULL(EP.EMPL,0) != 0)
-- 113
select @link_row = link_row from report_rows where link_table = @link_table and orders = 13
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '2' AND ISNULL(EP.EMPL,0) != 0)
-- 114
select @link_row = link_row from report_rows where link_table = @link_table and orders = 14
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '3' AND ISNULL(EP.EMPL,0) != 0)
-- 115
select @link_row = link_row from report_rows where link_table = @link_table and orders = 15
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '4' AND ISNULL(EP.EMPL,0) != 0)
-- 117
select @link_row = link_row from report_rows where link_table = @link_table and orders = 17
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '2' AND ISNULL(EP.EMPL,0) != 0)
-- 118
select @link_row = link_row from report_rows where link_table = @link_table and orders = 18
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '3' AND ISNULL(EP.EMPL,0) != 0)
-- 119
select @link_row = link_row from report_rows where link_table = @link_table and orders = 19
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '4' AND ISNULL(EP.EMPL,0) != 0)
-- 120
select @link_row = link_row from report_rows where link_table = @link_table and orders = 20
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '5' AND ISNULL(EP.EMPL,0) != 0)
-- 122
select @link_row = link_row from report_rows where link_table = @link_table and orders = 22
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where SEX = 2 AND ISNULL(EP.EMPL,0) != 0)
-- 123
select @link_row = link_row from report_rows where link_table = @link_table and orders = 23
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where SEX = 1 AND ISNULL(EP.EMPL,0) != 0)
-- **************************************************************
-- ***********************   6 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 6
-- 101
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 2 AND ISNULL(EI.EMPL,0) != 0)
-- 104
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '1' AND ISNULL(EI.EMPL,0) != 0)
-- 105
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '2' AND ISNULL(EI.EMPL,0) != 0)
-- 106
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '3' AND ISNULL(EI.EMPL,0) != 0)
-- 108
select @link_row = link_row from report_rows where link_table = @link_table and orders = 8
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '1' AND ISNULL(EI.EMPL,0) != 0)
-- 109
select @link_row = link_row from report_rows where link_table = @link_table and orders = 9
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '2' AND ISNULL(EI.EMPL,0) != 0)
-- 110
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '3' AND ISNULL(EI.EMPL,0) != 0)
-- 112
select @link_row = link_row from report_rows where link_table = @link_table and orders = 12
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '1' AND ISNULL(EI.EMPL,0) != 0)
-- 113
select @link_row = link_row from report_rows where link_table = @link_table and orders = 13
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '2' AND ISNULL(EI.EMPL,0) != 0)
-- 114
select @link_row = link_row from report_rows where link_table = @link_table and orders = 14
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '3' AND ISNULL(EI.EMPL,0) != 0)
-- 115
select @link_row = link_row from report_rows where link_table = @link_table and orders = 15
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '4' AND ISNULL(EI.EMPL,0) != 0)
-- 117
select @link_row = link_row from report_rows where link_table = @link_table and orders = 17
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '2' AND ISNULL(EI.EMPL,0) != 0)
-- 118
select @link_row = link_row from report_rows where link_table = @link_table and orders = 18
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '3' AND ISNULL(EI.EMPL,0) != 0)
-- 119
select @link_row = link_row from report_rows where link_table = @link_table and orders = 19
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '4' AND ISNULL(EI.EMPL,0) != 0)
-- 120
select @link_row = link_row from report_rows where link_table = @link_table and orders = 20
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '5' AND ISNULL(EI.EMPL,0) != 0)
-- 122
select @link_row = link_row from report_rows where link_table = @link_table and orders = 22
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where SEX = 2 AND ISNULL(EI.EMPL,0) != 0)
-- 123
select @link_row = link_row from report_rows where link_table = @link_table and orders = 23
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where SEX = 1 AND ISNULL(EI.EMPL,0) != 0)
-- **************************************************************
-- ***********************  9 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 9
-- 101
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 2 AND ISNULL(EP.EMPL,0) != 0 AND FIN in (2,4))
-- 104
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '1' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 105
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '2' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 106
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '3' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 108
select @link_row = link_row from report_rows where link_table = @link_table and orders = 8
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '1' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 109
select @link_row = link_row from report_rows where link_table = @link_table and orders = 9
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '2' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 110
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '3' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 112
select @link_row = link_row from report_rows where link_table = @link_table and orders = 12
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '1' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 113
select @link_row = link_row from report_rows where link_table = @link_table and orders = 13
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '2' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 114
select @link_row = link_row from report_rows where link_table = @link_table and orders = 14
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '3' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 115
select @link_row = link_row from report_rows where link_table = @link_table and orders = 15
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '4' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 117
select @link_row = link_row from report_rows where link_table = @link_table and orders = 17
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '2' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 118
select @link_row = link_row from report_rows where link_table = @link_table and orders = 18
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '3' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 119
select @link_row = link_row from report_rows where link_table = @link_table and orders = 19
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '4' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 120
select @link_row = link_row from report_rows where link_table = @link_table and orders = 20
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '5' AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 122
select @link_row = link_row from report_rows where link_table = @link_table and orders = 22
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where SEX = 2 AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- 123
select @link_row = link_row from report_rows where link_table = @link_table and orders = 23
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where SEX = 1 AND ISNULL(EP.EMPL,0) != 0 AND EP.FIN in (2,4))
-- **************************************************************
-- ***********************  10 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 10
-- 101
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 2 AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 104
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '1' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 105
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '2' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 106
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '3' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 108
select @link_row = link_row from report_rows where link_table = @link_table and orders = 8
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '1' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 109
select @link_row = link_row from report_rows where link_table = @link_table and orders = 9
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '2' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 110
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '3' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 112
select @link_row = link_row from report_rows where link_table = @link_table and orders = 12
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '1' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 113
select @link_row = link_row from report_rows where link_table = @link_table and orders = 13
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '2' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 114
select @link_row = link_row from report_rows where link_table = @link_table and orders = 14
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '3' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 115
select @link_row = link_row from report_rows where link_table = @link_table and orders = 15
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '4' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 117
select @link_row = link_row from report_rows where link_table = @link_table and orders = 17
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '2' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 118
select @link_row = link_row from report_rows where link_table = @link_table and orders = 18
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '3' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 119
select @link_row = link_row from report_rows where link_table = @link_table and orders = 19
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '4' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 120
select @link_row = link_row from report_rows where link_table = @link_table and orders = 20
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '5' AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 122
select @link_row = link_row from report_rows where link_table = @link_table and orders = 22
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where SEX = 2 AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
-- 123
select @link_row = link_row from report_rows where link_table = @link_table and orders = 23
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where SEX = 1 AND ISNULL(EI.EMPL,0) != 0 AND EI.FIN in (2,4))
--************************************************--
--********** СПРАВКА 1 И 2 К РАЗДЕЛУ 1 ***********--
--************************************************--
-- выбор таблицы
select @link_table = link_table from report_tables where link_form = @link_form and orders = 2
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 3
-----------------------------------------------------------------------------------------
--------------------------- СПРАВКА 1 -----------------------------------------------------
-------------------------------------------------------------------------------------------
CREATE TABLE #TEMP(EMPL INT)
-------------------------------------------------------------------------------------------
-- 132
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL_LINK FROM EMPL_ATTEST
WHERE YEAR(DATE) = YEAR(@date_begin) AND DATE <= @date_begin AND EMPL_LINK IN (SELECT LINK FROM #EMPLS_INFO WHERE GOSSL = 1)
	AND RTRIM(LTRIM((SELECT TOP 1 NAME FROM DICTIONARY_ATT_RESH_COM WHERE LINK = ATT_LINK))) LIKE 'соотв%'

select @link_row = link_row from report_rows where link_table = @link_table and orders = 2
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 133
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
-- 134
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
-- 135
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL_LINK FROM EMPL_ATTEST
WHERE YEAR(DATE) = YEAR(@date_begin) AND DATE <= @date_begin AND EMPL_LINK IN (SELECT LINK FROM #EMPLS_INFO WHERE GOSSL = 1)
	AND RTRIM(LTRIM((SELECT TOP 1 NAME FROM DICTIONARY_ATT_RESH_COM WHERE LINK = ATT_LINK))) LIKE 'не соотв%'

select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 136
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL_LINK FROM EMPL_RESERV
WHERE YEAR(DATE) = YEAR(@date_begin) AND DATE <= @date_begin AND EMPL_LINK IN (SELECT LINK FROM #EMPLS_INFO WHERE GOSSL = 1)

select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 137
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
-- 138
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL_LINK FROM EMPL_CHIN
WHERE YEAR(DATE) = YEAR(@date_begin) AND DATE <= @date_begin AND EMPL_LINK IN (SELECT LINK FROM #EMPLS_INFO WHERE GOSSL = 1)

select @link_row = link_row from report_rows where link_table = @link_table and orders = 8
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 139
select @link_row = link_row from report_rows where link_table = @link_table and orders = 9
-- 140
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
-- 141
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL_LINK FROM ITEM_PENALTY
WHERE ACTIVE = 1 AND YEAR(PEN_DATE) = YEAR(@date_begin) AND PEN_DATE <= @date_begin AND EMPL_LINK IN (SELECT LINK FROM #EMPLS_INFO WHERE GOSSL = 1)

select @link_row = link_row from report_rows where link_table = @link_table and orders = 11
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 142
DELETE FROM #TEMP
INSERT #TEMP
SELECT EMPL_LINK FROM ITEM_MOVE
WHERE NEW_FACE = 1 AND ACTIVE = 1 AND YEAR(DATE_BEGIN) = YEAR(@date_begin) AND DATE_BEGIN <= @date_begin
	AND ORDER_LINK IN (SELECT LINK FROM ORDERS WHERE DEP_LINK = (SELECT DEP_LINK FROM USER_DEP))

select @link_row = link_row from report_rows where link_table = @link_table and orders = 12
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 143
DELETE FROM #TEMP
INSERT #TEMP
SELECT EMPL_LINK FROM ITEM_MOVE
WHERE NEW_FACE = 1 AND ACTIVE = 1 AND YEAR(DATE_BEGIN) = YEAR(@date_begin) AND DATE_BEGIN <= @date_begin AND RTRIM(LTRIM(USL_PR)) LIKE '%конкурс%'
	AND ORDER_LINK IN (SELECT LINK FROM ORDERS WHERE DEP_LINK = (SELECT DEP_LINK FROM USER_DEP))

select @link_row = link_row from report_rows where link_table = @link_table and orders = 13
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 144
DELETE FROM #TEMP
INSERT #TEMP
SELECT EMPL_LINK FROM ITEM_MOVE
WHERE NEW_FACE = 1 AND ACTIVE = 1 AND YEAR(DATE_BEGIN) = YEAR(@date_begin) AND DATE_BEGIN <= @date_begin AND RTRIM(LTRIM(USL_PR)) LIKE '%резерв%'
	AND ORDER_LINK IN (SELECT LINK FROM ORDERS WHERE DEP_LINK = (SELECT DEP_LINK FROM USER_DEP))

select @link_row = link_row from report_rows where link_table = @link_table and orders = 14
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 145
DELETE FROM #TEMP
INSERT #TEMP
SELECT EMPL_LINK FROM ITEM_MOVE
WHERE NEW_FACE = 1 AND ACTIVE = 1 AND YEAR(DATE_BEGIN) = YEAR(@date_begin) AND DATE_BEGIN <= @date_begin AND (ISNULL(DATE_END2,'99991231') != '99991231' OR ISNULL(TEMP_LINK,0) = 1)
	AND ORDER_LINK IN (SELECT LINK FROM ORDERS WHERE DEP_LINK = (SELECT DEP_LINK FROM USER_DEP))

select @link_row = link_row from report_rows where link_table = @link_table and orders = 15
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 146
DELETE FROM #TEMP
INSERT #TEMP
SELECT EMPL_LINK FROM ITEM_DIS_FACE WHERE ACTIVE = 1 AND YEAR(DIS_DATE) = YEAR(@date_begin) AND DIS_DATE <= @date_begin
	AND ORDER_LINK IN (SELECT LINK FROM ORDERS WHERE DEP_LINK = (SELECT DEP_LINK FROM USER_DEP))

select @link_row = link_row from report_rows where link_table = @link_table and orders = 16
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 147
DELETE FROM #TEMP
INSERT #TEMP
SELECT EMPL_LINK FROM ITEM_DIS_FACE DF LEFT JOIN DICTIONARY_PUV P ON DF.REASON = P. LINK
WHERE ACTIVE = 1 AND YEAR(DIS_DATE) = YEAR(@date_begin) AND DIS_DATE <= @date_begin AND RTRIM(LTRIM(CODE)) = '0300'
	AND ORDER_LINK IN (SELECT LINK FROM ORDERS WHERE DEP_LINK = (SELECT DEP_LINK FROM USER_DEP))

select @link_row = link_row from report_rows where link_table = @link_table and orders = 17
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 148
select @link_row = link_row from report_rows where link_table = @link_table and orders = 18
-------------------------------------------------------------------------------------------
--------------------------- СПРАВКА 2 -----------------------------------------------------
-------------------------------------------------------------------------------------------
-- 151
select @link_row = link_row from report_rows where link_table = @link_table and orders = 19
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FORM = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FORM = 1))
-- 152
select @link_row = link_row from report_rows where link_table = @link_table and orders = 20
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FORM IN (2,3))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FORM IN (2,3)))
-- 153
select @link_row = link_row from report_rows where link_table = @link_table and orders = 21
-- 154
select @link_row = link_row from report_rows where link_table = @link_table and orders = 22

-- 155
select @link_row = link_row from report_rows where link_table = @link_table and orders = 23
-- 156
select @link_row = link_row from report_rows where link_table = @link_table and orders = 24
-------------------------------------------------------------------------------------------
--------------------------- КРОМЕ ТОГО ----------------------------------------------------
-------------------------------------------------------------------------------------------
-- 161
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL FROM #EMPL_INCQUAL EI WHERE EXISTS(SELECT * FROM ITEM_DIS_FACE WHERE ACTIVE = 1 AND EMPL_LINK = EI.EMPL)
INSERT #TEMP
SELECT DISTINCT EMPL FROM #EMPL_PROFP EP WHERE EXISTS(SELECT * FROM ITEM_DIS_FACE WHERE ACTIVE = 1 AND EMPL_LINK = EP.EMPL)

select @link_row = link_row from report_rows where link_table = @link_table and orders = 25
insert into report_summa
select @varKSsFLink,@link_col,@link_row, (SELECT COUNT(*) FROM (SELECT DISTINCT EMPL FROM #TEMP) T)
-- 162
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL FROM #EMPL_INCQUAL EI WHERE EXISTS(SELECT * FROM ITEM_DIS_FACE WHERE ACTIVE = 1 AND EMPL_LINK = EI.EMPL)
INSERT #TEMP
SELECT DISTINCT EMPL FROM #EMPL_PROFP EP WHERE EXISTS(SELECT * FROM ITEM_DIS_FACE WHERE ACTIVE = 1 AND EMPL_LINK = EP.EMPL)

select @link_row = link_row from report_rows where link_table = @link_table and orders = 26
insert into report_summa
select @varKSsFLink,@link_col,@link_row, (SELECT COUNT(*) FROM (SELECT DISTINCT EMPL FROM #TEMP) T)
-- 163
select @link_row = link_row from report_rows where link_table = @link_table and orders = 27
-------------------------------------------------------------------------------------------
DROP TABLE #TEMP
--*******************************--
--********** РАЗДЕЛ 2 ***********--
--*******************************--
-- выбор таблицы
select @link_table = link_table from report_tables where link_form = @link_form and orders = 3
-- заполнение данных
-- **************************************************************
-- ***********************   3 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 3

-- 201
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 2 AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 2 AND EP.DIR = 1))
-- 204
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '1' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '1' AND EP.DIR in (1,2,3,4,5,6)))
-- 205
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '2' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '2' AND EP.DIR in (1,2,3,4,5,6)))
-- 206
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '3' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '3' AND EP.DIR in (1,2,3,4,5,6)))
-- 208
select @link_row = link_row from report_rows where link_table = @link_table and orders = 8
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '1' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '1' AND EP.DIR in (1,2,3,4,5,6)))
-- 209
select @link_row = link_row from report_rows where link_table = @link_table and orders = 9
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '2' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '2' AND EP.DIR in (1,2,3,4,5,6)))
-- 210
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '3' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '3' AND EP.DIR in (1,2,3,4,5,6)))
-- 212
select @link_row = link_row from report_rows where link_table = @link_table and orders = 12
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '1' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '1' AND EP.DIR in (1,2,3,4,5,6)))
-- 213
select @link_row = link_row from report_rows where link_table = @link_table and orders = 13
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '2' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '2' AND EP.DIR in (1,2,3,4,5,6)))
-- 214
select @link_row = link_row from report_rows where link_table = @link_table and orders = 14
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '3' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '3' AND EP.DIR in (1,2,3,4,5,6)))
-- 215
select @link_row = link_row from report_rows where link_table = @link_table and orders = 15
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '4' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '4' AND EP.DIR in (1,2,3,4,5,6)))
-- 217
select @link_row = link_row from report_rows where link_table = @link_table and orders = 17
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '2' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '2' AND EP.DIR in (1,2,3,4,5,6)))
-- 218
select @link_row = link_row from report_rows where link_table = @link_table and orders = 18
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '3' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '3' AND EP.DIR in (1,2,3,4,5,6)))
-- 219
select @link_row = link_row from report_rows where link_table = @link_table and orders = 19
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '4' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '4' AND EP.DIR in (1,2,3,4,5,6)))
-- 220
select @link_row = link_row from report_rows where link_table = @link_table and orders = 20
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '5' AND EI.DIR in (1,2,3,4,5,6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '5' AND EP.DIR in (1,2,3,4,5,6)))
-- **************************************************************
-- ***********************   4 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 4
-- 201
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 2 AND EI.DIR NOT IN (6) )
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 2 AND EP.DIR IN (6)))
-- 204
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '1' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '1' AND EP.DIR IN (6)))
-- 205
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '2' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '2' AND EP.DIR IN (6)))
-- 206
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '3' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '3' AND EP.DIR IN (6)))
-- 208
select @link_row = link_row from report_rows where link_table = @link_table and orders = 8
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '1' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '1' AND EP.DIR IN (6)))
-- 209
select @link_row = link_row from report_rows where link_table = @link_table and orders = 9
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '2' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '2' AND EP.DIR IN (6)))
-- 210
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '3' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '3' AND EP.DIR IN (6)))
-- 212
select @link_row = link_row from report_rows where link_table = @link_table and orders = 12
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '1' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '1' AND EP.DIR IN (6)))
-- 213
select @link_row = link_row from report_rows where link_table = @link_table and orders = 13
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '2' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '2' AND EP.DIR IN (6)))
-- 214
select @link_row = link_row from report_rows where link_table = @link_table and orders = 14
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '3' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '3' AND EP.DIR IN (6)))
-- 215
select @link_row = link_row from report_rows where link_table = @link_table and orders = 15
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '4' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '4' AND EP.DIR IN (6)))
-- 217
select @link_row = link_row from report_rows where link_table = @link_table and orders = 17
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '2' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '2' AND EP.DIR IN (6)))
-- 218
select @link_row = link_row from report_rows where link_table = @link_table and orders = 18
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '3' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '3' AND EP.DIR IN (6)))
-- 219
select @link_row = link_row from report_rows where link_table = @link_table and orders = 19
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '4' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '4' AND EP.DIR IN (6)))
-- 220
select @link_row = link_row from report_rows where link_table = @link_table and orders = 20
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '5' AND EI.DIR IN (6))
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '5' AND EP.DIR IN (6)))
-- **************************************************************
-- ***********************   5 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 5
-- 201
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 2 AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 2 AND EP.GOS = 1))
-- 204
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '1' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '1' AND EP.GOS = 1))
-- 205
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '2' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '2' AND EP.GOS = 1))
-- 206
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '3' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '3' AND EP.GOS = 1))
-- 208
select @link_row = link_row from report_rows where link_table = @link_table and orders = 8
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '1' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '1' AND EP.GOS = 1))
-- 209
select @link_row = link_row from report_rows where link_table = @link_table and orders = 9
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '2' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '2' AND EP.GOS = 1))
-- 210
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '3' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '3' AND EP.GOS = 1))
-- 212
select @link_row = link_row from report_rows where link_table = @link_table and orders = 12
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '1' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '1' AND EP.GOS = 1))
-- 213
select @link_row = link_row from report_rows where link_table = @link_table and orders = 13
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '2' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '2' AND EP.GOS = 1))
-- 214
select @link_row = link_row from report_rows where link_table = @link_table and orders = 14
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '3' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '3' AND EP.GOS = 1))
-- 215
select @link_row = link_row from report_rows where link_table = @link_table and orders = 15
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '4' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '4' AND EP.GOS = 1))
-- 217
select @link_row = link_row from report_rows where link_table = @link_table and orders = 17
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '2' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '2' AND EP.GOS = 1))
-- 218
select @link_row = link_row from report_rows where link_table = @link_table and orders = 18
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '3' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '3' AND EP.GOS = 1))
-- 219
select @link_row = link_row from report_rows where link_table = @link_table and orders = 19
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '4' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '4' AND EP.GOS = 1))
-- 220
select @link_row = link_row from report_rows where link_table = @link_table and orders = 20
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '5' AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '5' AND EP.GOS = 1))
-- **************************************************************
-- ***********************  6 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 6
-- **************************************************************
-- ***********************  7 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 7
-- 201
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 2 AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 2 AND EP.GOS = 2))
-- 204
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '1' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '1' AND EP.GOS = 2))
-- 205
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '2' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '2' AND EP.GOS = 2))
-- 206
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '3' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '1' AND E.GR_GOS_CODE = '3' AND EP.GOS = 2))
-- 208
select @link_row = link_row from report_rows where link_table = @link_table and orders = 8
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '1' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '1' AND EP.GOS = 2))
-- 209
select @link_row = link_row from report_rows where link_table = @link_table and orders = 9
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '2' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '2' AND EP.GOS = 2))
-- 210
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '3' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '2' AND E.GR_GOS_CODE = '3' AND EP.GOS = 2))
-- 212
select @link_row = link_row from report_rows where link_table = @link_table and orders = 12
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '1' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '1' AND EP.GOS = 2))
-- 213
select @link_row = link_row from report_rows where link_table = @link_table and orders = 13
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '2' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '2' AND EP.GOS = 2))
-- 214
select @link_row = link_row from report_rows where link_table = @link_table and orders = 14
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '3' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '3' AND EP.GOS = 2))
-- 215
select @link_row = link_row from report_rows where link_table = @link_table and orders = 15
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '4' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '3' AND E.GR_GOS_CODE = '4' AND EP.GOS = 2))
-- 217
select @link_row = link_row from report_rows where link_table = @link_table and orders = 17
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '2' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '2' AND EP.GOS = 2))
-- 218
select @link_row = link_row from report_rows where link_table = @link_table and orders = 18
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '3' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '3' AND EP.GOS = 2))
-- 219
select @link_row = link_row from report_rows where link_table = @link_table and orders = 19
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '4' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '4' AND EP.GOS = 2))
-- 220
select @link_row = link_row from report_rows where link_table = @link_table and orders = 20
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '5' AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 1 AND E.KAT_GOS_CODE = '4' AND E.GR_GOS_CODE = '5' AND EP.GOS = 2))

-- **************************************************************
-- ***********************  8 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 8

--*******************************--
--********** РАЗДЕЛ 4 ***********--
--*******************************--
-- выбор таблицы
select @link_table = link_table from report_tables where link_form = @link_form and orders = 4
-- заполнение данных
-- **************************************************************
-- ***********************   4 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 4
--301
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FIN IN (1,2))
--302
select @link_row = link_row from report_rows where link_table = @link_table and orders = 2
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FIN = 2)
--303
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FIN IN (3, 4))
--304
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FIN = 4)
--305
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FIN IN (7, 8, 9))
--306
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FIN = 7)
--307
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FIN = 8)
-- **************************************************************
-- ***********************   5 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 5
--301
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FIN IN (1,2))
--302
select @link_row = link_row from report_rows where link_table = @link_table and orders = 2
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FIN = 2)
--303
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FIN IN (3, 4))
--304
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FIN = 4)
--305
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FIN IN (7, 8, 9))
--306
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FIN = 7)
--307
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FIN = 8)


DROP TABLE #EMPLS_INFO
DROP TABLE #EMPL_INCQUAL
DROP TABLE #EMPL_PROFP
select '' as Val


GO


GRANT EXECUTE ON dbo.[RJ_AUTOFILL_2GS_GZ_2016] TO PUBLIC

GO




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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE dbo.SD_O_ESN_TABLE_SAVE
	@intLINK				int,
	@intORDERS			int,
	@intLINK_EMPL		int,
	@numSUMMA_BASE 	numeric(18,2)=0.0,
	@numCALC_TAX		numeric(18,2)=0.0,
	@numDED_M			numeric(18,2)=0.0,
	@numINV_M			numeric(18,2)=0.0,
	@numSUM_DED 		numeric(18,2)=0.0,
	@numSUMMA			numeric(18,2)=0.0,
	@numTOTAL_DED		numeric(18,2)=0.0,
	@numTOTAL_SUM		numeric(18,2)=0.0,
	@numTOTAL_TAX		numeric(18,2)=0.0, 
	@intLINK_PAY		int,
	@intLINK_VKR 		int,
	@LINK_EKR			INT,
	@DEL				TINYINT = 0,
	@PERC				numeric(18,2)=0.0,
	@TARIF				INT=null,	
	@SPECO				INT = null,
	@intLINK_VKR2 		int = NULL

AS
DECLARE @SQLError			tinyint,
		  @trancount	int,		
		  @strVALUE		varchar(7000),
		  @tintSTATUS	int,
		  @RowCount		int,
		  @linkFace 	int	

SET @trancount = @@TRANCOUNT

SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

IF @intLINK_VKR2 IS NULL
	SET @intLINK_VKR2 = @intLINK_VKR

SELECT @linkFace = PERS_LINK FROM dbo.EMPL WHERE LINK = @intLINK_EMPL
SELECT @tintSTATUS = dbo.IS_INVALID(@linkFace,dbo.SalaryPeriodCalcBegin())

IF @intLINK_EMPL IS NULL OR @intLINK_PAY IS NULL OR @intLINK_VKR IS NULL OR @LINK_EKR IS NULL
BEGIN
	ROLLBACK
	RETURN 8
END

IF ISNULL(@DEL,0) = 0

	IF NOT EXISTS (SELECT LINK_UP FROM DBO.SDOC_ESN_TABLE WHERE LINK_UP = @intLINK AND LINK_EMPL = @intLINK_EMPL AND LINK_PAY = @intLINK_PAY AND LINK_VKR = @intLINK_VKR AND LINK_EKR = @LINK_EKR)
		INSERT INTO SDOC_ESN_TABLE WITH (ROWLOCK) (LINK_UP,ORDERS,LINK_EMPL,SUMMA_BASE,CALC_TAX,DED_M,INV_M,SUM_DED,SUMMA, TOTAL_DED,TOTAL_SUM,TOTAL_TAX,LINK_PAY,LINK_VKR,[STATUS],LINK_EKR, PERC, TARIF, SPECO, LINK_VKR2)
		VALUES (@intLINK,@intORDERS,@intLINK_EMPL,@numSUMMA_BASE,@numCALC_TAX,@numDED_M,@numINV_M,@numSUM_DED,@numSUMMA,
				@numTOTAL_DED,@numTOTAL_SUM,@numTOTAL_TAX,@intLINK_PAY,@intLINK_VKR,@tintSTATUS,@LINK_EKR, @PERC, @TARIF, @SPECO, @intLINK_VKR2)

	ELSE
		UPDATE 
			DBO.SDOC_ESN_TABLE
		SET
			ORDERS = @intORDERS,
			SUMMA_BASE = @numSUMMA_BASE,
			CALC_TAX = @numCALC_TAX,
			DED_M = @numDED_M,
			INV_M = @numINV_M,
			SUM_DED = @numSUM_DED,
			SUMMA = @numSUMMA, 
			TOTAL_DED = @numTOTAL_DED,
			TOTAL_SUM = @numTOTAL_SUM,
			TOTAL_TAX = @numTOTAL_TAX,
			[STATUS] = @tintSTATUS,
			PERC = @PERC,
			TARIF = @TARIF,
			SPECO = @SPECO,
			LINK_VKR2 = @intLINK_VKR2
		WHERE 
			LINK_UP = @intLINK AND LINK_EMPL = @intLINK_EMPL AND LINK_PAY = @intLINK_PAY AND LINK_VKR = @intLINK_VKR AND LINK_EKR = @LINK_EKR
ELSE
		DELETE FROM DBO.SDOC_ESN_TABLE
		WHERE LINK_UP = @intLINK AND LINK_EMPL = @intLINK_EMPL AND LINK_PAY = @intLINK_PAY AND LINK_VKR = @intLINK_VKR AND LINK_EKR = @LINK_EKR

SELECT @SQLError = @@ERROR, @intLINK = @@IDENTITY
IF @SQLError <> 0
BEGIN
	ROLLBACK
	RETURN 7
END

WHILE @@TRANCOUNT > @trancount
	COMMIT TRAN
RETURN 0




GO


GRANT EXECUTE ON dbo.[SD_O_ESN_TABLE_SAVE] TO PUBLIC

GO

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

GO

--- МНОГОГРАФНАЯ КАРТОЧКА --- 
-- SELECT * FROM S_ACCOUNTS WHERE CODE = '1.401.01'
-- SELECT * FROM dbo.BK_GetTableDictionByAP ('EKR') 
-- EXEC [dbo].BK_REPORT_MANYGRAPH_CARD '20070101', '20071231', 1486, 0, 'EKR'
CREATE     PROCEDURE dbo.BK_REPORT_MANYGRAPH_CARD 
	@dDateSTART datetime	/* Начало расч. периода */,
	@dDateEND datetime	/* Конец расч. периода */,
	@nSel_Spr1 int		/* Счет */,
	@nPRN_REST	INT	/* -- Выводить остатки по счету -- */,
	@strCODE_AP	VARCHAR (60) = 'ACCOUNT',
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК --
	@cVal_KAU char(1) = '', @nOtborLinkKAU int = 0	-- Отбор КАУ
AS 
BEGIN
	DECLARE
		@cCROSS_TABLE_DB	VARCHAR (100),
		@cCROSS_TABLE_KT	VARCHAR (100),
		@intCOUNTER		INT,
		@cCOUNTER		VARCHAR (10),
		@intMAX_REC		INT,
		@cSQL_STR		VARCHAR (1000),
		@DEP_NAME		VARCHAR (254),
		@DEP_OKPO		VARCHAR (20),
		@DEP_LINK		INT,
		@GLBUH_NAME		VARCHAR (100),
		@intCOUNT_COLROW	INT,
		@REST_BEGIN		NUMERIC (28,4),
		@REST_END		NUMERIC (28,4),
		@dDATE_REST_E		DATETIME,
		@cDATE_REST_E		VARCHAR (10)		

	SET @intMAX_REC = 10

	SELECT @DEP_LINK = LINK, @DEP_OKPO = OKPO, @DEP_NAME = [NAME]
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = COALESCE (dbo.BK_GetDepZB (), dbo.GetOwnDepLink ())

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

	--- ОТБОР КБК --- 
	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_KAU TABLE (LINK INT)
	IF LEN (@cVal_KAU) > 0
		INSERT INTO @TAB_KAU
		SELECT
			AP.LINK
		FROM dbo.KAU AP 
		INNER JOIN dbo.OBJECT_VAR_KAU OVR ON (OVR.RECORD = AP.LINK)
		WHERE
			OVR.LINK_UP = @nOtborLinkKAU
	ELSE
		SET @nOtborLinkKAU = -1

	-- Входящий остаток по счету -- 
	SELECT
		@REST_BEGIN = CASE 
						WHEN S_ACTIVE = 1 THEN SUM (D_SUMMA)
						WHEN S_PASSIVE = 1 THEN SUM (K_SUMMA)
				END
	FROM dbo.ARestTableByDate (@dDateSTART, @nSel_Spr1) R
	INNER JOIN dbo.S_ACCOUNTS SA ON (R.ACCOUNT = SA.LINK)
	INNER JOIN @TAB_KBK KBK ON (KBK.LINK_KBK = ISNULL (R.KBK, 0))
	WHERE
		R.DEP_LINK = @DEP_LINK
		AND (@nOtborLinkKAU = -1
				OR @nOtborLinkKAU > 0 AND EXISTS (SELECT * FROM @TAB_KAU TTT
													WHERE TTT.LINK = R.KAU)
				)									
	GROUP BY
		S_ACTIVE, S_PASSIVE

	/* -- Исходящий остаток по счету -- */
	SET @dDATE_REST_E = DATEADD (DAY, 1, @dDateEND)
	SET @cDATE_REST_E = CONVERT (VARCHAR (10), @dDATE_REST_E, 104)
	SELECT
		@REST_END = CASE 
						WHEN S_ACTIVE = 1 THEN SUM (D_SUMMA)
						WHEN S_PASSIVE = 1 THEN SUM (K_SUMMA)
				END
	FROM dbo.ARestTableByDate (@dDATE_REST_E, @nSel_Spr1) R
	INNER JOIN dbo.S_ACCOUNTS SA ON (R.ACCOUNT = SA.LINK)
	INNER JOIN @TAB_KBK KBK ON (KBK.LINK_KBK = ISNULL (R.KBK, 0))
	WHERE
		R.DEP_LINK = @DEP_LINK
		AND (@nOtborLinkKAU = -1
				OR @nOtborLinkKAU > 0 AND EXISTS (SELECT * FROM @TAB_KAU TTT
													WHERE TTT.LINK = R.KAU)
				)									
	GROUP BY S_ACTIVE, S_PASSIVE

	SELECT @REST_BEGIN = ISNULL (@REST_BEGIN, 0), @REST_END = ISNULL (@REST_END, 0)

	--- БЕРЕМ ВСЕ ДЕБЕТОВЫЕ ОБОРОТЫ ЗА ПЕРИОД ПО СЧЕТУ (КРЕДИТОВАЯ КОРРЕСПОНДЕНЦИЯ) --- 
	CREATE TABLE #ACCT_IN_DB
			(DATE_OP		[DATETIME],
				JO_NUM		[VARCHAR] (10),
				NAME_OPER	[VARCHAR] (254),
				AC		[VARCHAR] (60),
				SS		[NUMERIC] (28,4),
				RB		[NUMERIC] (28,4),
				RE		[NUMERIC] (28,4),
				REST_B		[NUMERIC] (28,4),
				REST_E		[NUMERIC] (28,4),
				DATE_E		[VARCHAR] (10))

	INSERT INTO #ACCT_IN_DB
	SELECT OB.DATE_PROV,
		ISNULL (OP.JOUR_CODE, ''),
		OB.NAME_OPER,
		CASE
			WHEN @strCODE_AP = 'ACCOUNT'
				THEN ISNULL (dbo.BK_GetAcctFullCode1 (G_KT.ACCOUNT,
									G_KT.KBK,
									G_KT.SGU,
									DEFAULT, DEFAULT), '')
			ELSE AP.AP_CODE
		END,
		OB.SUMMA,
		0, 0,
		@REST_BEGIN,
		@REST_END,
		@cDATE_REST_E
	FROM dbo.BK_GetTableOborotByDate1 (@dDateSTART, @dDateEND, 0, @nSel_Spr1, @DEP_LINK) OB
	INNER JOIN @TAB_KBK KBK ON (KBK.LINK_KBK = OB.KBK)
	LEFT JOIN dbo.G_PROV_AP G_KT ON (G_KT.LINK_UP = OB.LINK_G2
		AND G_KT.DB_KR = 1)
	LEFT JOIN dbo.BK_GetTableDictionByAP (@strCODE_AP) AP ON (AP.LINK_AP = CASE
									WHEN @strCODE_AP = 'EKR' THEN OB.EKR
									WHEN @strCODE_AP = 'KAU' THEN OB.KAU
								END)
	LEFT OUTER JOIN dbo.BK_TYPE_ECONOM_OPER OP ON (OP.LINK = OB.XOZ_OPER)
	WHERE 
		(@strCODE_AP = 'ACCOUNT' 
			OR (@strCODE_AP = 'EKR' AND AP.LINK_AP IS NOT NULL)
			OR (@strCODE_AP = 'KAU' AND AP.LINK_AP IS NOT NULL)
		)
		AND (@nOtborLinkKAU = -1
				OR @nOtborLinkKAU > 0 AND EXISTS (SELECT * FROM @TAB_KAU TTT
													WHERE TTT.LINK = OB.KAU)
				)									

	--- БЕРЕМ ВСЕ КРЕДИТОВЫЕ ОБОРОТЫ ЗА ПЕРИОД ПО СЧЕТУ (ДЕБЕТОВАЯ КОРРЕСПОНДЕНЦИЯ) --- 
	CREATE TABLE #ACCT_IN_KT (DATE_OP		[DATETIME],
				JO_NUM		[VARCHAR] (10),
				NAME_OPER	[VARCHAR] (254),
				AC		[VARCHAR] (60),
				SS		[NUMERIC] (28,4),
				RB		[NUMERIC] (28,4),
				RE		[NUMERIC] (28,4),
				REST_B		[NUMERIC] (28,4),
				REST_E		[NUMERIC] (28,4),
				DATE_E		[VARCHAR] (10))

	INSERT INTO #ACCT_IN_KT
	SELECT OB.DATE_PROV,
		ISNULL (OP.JOUR_CODE, ''),
		OB.NAME_OPER,
		CASE
			WHEN @strCODE_AP = 'ACCOUNT'
				THEN ISNULL (dbo.BK_GetAcctFullCode1 (G_DB.ACCOUNT,
									G_DB.KBK,
									G_DB.SGU,
									DEFAULT,
									DEFAULT), '')
			ELSE AP.AP_CODE
		END,
		OB.SUMMA,
		0, 0,
		@REST_BEGIN,
		@REST_END,
		@cDATE_REST_E
	FROM dbo.BK_GetTableOborotByDate1 (@dDateSTART, @dDateEND, 1, @nSel_Spr1, @DEP_LINK) OB
	INNER JOIN @TAB_KBK KBK ON (KBK.LINK_KBK = OB.KBK)
	LEFT JOIN dbo.G_PROV_AP G_DB ON (G_DB.LINK_UP = OB.LINK_G2
		AND G_DB.DB_KR = 0)
	LEFT JOIN dbo.BK_GetTableDictionByAP (@strCODE_AP) AP ON (AP.LINK_AP = CASE
									WHEN @strCODE_AP = 'EKR' THEN OB.EKR
									WHEN @strCODE_AP = 'KAU' THEN OB.KAU
								END)
	LEFT OUTER JOIN dbo.BK_TYPE_ECONOM_OPER OP ON (OP.LINK = OB.XOZ_OPER)
	WHERE 
		(@strCODE_AP = 'ACCOUNT' 
			OR (@strCODE_AP = 'EKR' AND AP.LINK_AP IS NOT NULL)
			OR (@strCODE_AP = 'KAU' AND AP.LINK_AP IS NOT NULL)
			)
		AND (@nOtborLinkKAU = -1
				OR @nOtborLinkKAU > 0 AND EXISTS (SELECT * FROM @TAB_KAU TTT
													WHERE TTT.LINK = OB.KAU)
				)				

	--- Остатки по аналитике ---
	IF @strCODE_AP IN ('EKR', 'KAU')
	BEGIN
		-- Входящие ---
		UPDATE T_DB SET RB = ISNULL (R1.R_SUM, 0)
		FROM #ACCT_IN_DB T_DB
		LEFT JOIN dbo.BK_GetTableDictionByAP (@strCODE_AP) AP ON AP.AP_CODE = T_DB.AC
		LEFT JOIN (SELECT CASE 
					WHEN S_ACTIVE = 1 THEN SUM (D_SUMMA)
					WHEN S_PASSIVE = 1 THEN SUM (K_SUMMA)
				END AS R_SUM,
				CASE
					WHEN @strCODE_AP = 'EKR' THEN ISNULL (R.EKR, 0)
					WHEN @strCODE_AP = 'KAU' THEN ISNULL (R.KAU, 0)
				END AS AP
			FROM dbo.ARestTableByDate (@dDateSTART, @nSel_Spr1) R
			INNER JOIN dbo.S_ACCOUNTS SA ON (R.ACCOUNT = SA.LINK)
			INNER JOIN @TAB_KBK KBK ON (KBK.LINK_KBK = ISNULL (R.KBK, 0))
			WHERE R.DEP_LINK = @DEP_LINK
			GROUP BY S_ACTIVE, S_PASSIVE,
				CASE
					WHEN @strCODE_AP = 'EKR' THEN ISNULL (R.EKR, 0)
					WHEN @strCODE_AP = 'KAU' THEN ISNULL (R.KAU, 0)
				END
			) 
				AS R1 ON R1.AP = AP.LINK_AP

		UPDATE T_KT SET RB = R1.R_SUM
		FROM #ACCT_IN_KT T_KT
		LEFT JOIN dbo.BK_GetTableDictionByAP (@strCODE_AP) AP ON AP.AP_CODE = T_KT.AC
		LEFT JOIN (SELECT CASE 
					WHEN S_ACTIVE = 1 THEN SUM (D_SUMMA)
					WHEN S_PASSIVE = 1 THEN SUM (K_SUMMA)
				END AS R_SUM,
				CASE
					WHEN @strCODE_AP = 'EKR' THEN ISNULL (R.EKR, 0)
					WHEN @strCODE_AP = 'KAU' THEN ISNULL (R.KAU, 0)
				END AS AP
			FROM dbo.ARestTableByDate (@dDateSTART, @nSel_Spr1) R
			INNER JOIN dbo.S_ACCOUNTS SA ON (R.ACCOUNT = SA.LINK)
			INNER JOIN @TAB_KBK KBK ON (KBK.LINK_KBK = ISNULL (R.KBK, 0))
			WHERE R.DEP_LINK = @DEP_LINK
			GROUP BY S_ACTIVE, S_PASSIVE,
				CASE
					WHEN @strCODE_AP = 'EKR' THEN ISNULL (R.EKR, 0)
					WHEN @strCODE_AP = 'KAU' THEN ISNULL (R.KAU, 0)
				END
			) 
				AS R1 ON R1.AP = AP.LINK_AP

		-- Исходящие ---
		UPDATE T_DB SET RE = R1.R_SUM
		FROM #ACCT_IN_DB T_DB
		LEFT JOIN dbo.BK_GetTableDictionByAP (@strCODE_AP) AP ON AP.AP_CODE = T_DB.AC
		LEFT JOIN (SELECT CASE 
					WHEN S_ACTIVE = 1 THEN SUM (D_SUMMA)
					WHEN S_PASSIVE = 1 THEN SUM (K_SUMMA)
				END AS R_SUM,
				CASE
					WHEN @strCODE_AP = 'EKR' THEN ISNULL (R.EKR, 0)
					WHEN @strCODE_AP = 'KAU' THEN ISNULL (R.KAU, 0)
				END AS AP
			FROM dbo.ARestTableByDate (@dDATE_REST_E, @nSel_Spr1) R
			INNER JOIN @TAB_KBK KBK ON (KBK.LINK_KBK = ISNULL (R.KBK, 0))
			INNER JOIN dbo.S_ACCOUNTS SA ON (R.ACCOUNT = SA.LINK)
			WHERE R.DEP_LINK = @DEP_LINK
			GROUP BY S_ACTIVE, S_PASSIVE,
				CASE
					WHEN @strCODE_AP = 'EKR' THEN ISNULL (R.EKR, 0)
					WHEN @strCODE_AP = 'KAU' THEN ISNULL (R.KAU, 0)
				END
			) 
				AS R1 ON AP = AP.LINK_AP

		UPDATE T_KT SET RE = R1.R_SUM
		FROM #ACCT_IN_KT T_KT
		LEFT JOIN dbo.BK_GetTableDictionByAP (@strCODE_AP) AP ON AP.AP_CODE = T_KT.AC
		LEFT JOIN (SELECT CASE 
					WHEN S_ACTIVE = 1 THEN SUM (D_SUMMA)
					WHEN S_PASSIVE = 1 THEN SUM (K_SUMMA)
				END AS R_SUM,
				CASE
					WHEN @strCODE_AP = 'EKR' THEN ISNULL (R.EKR, 0)
					WHEN @strCODE_AP = 'KAU' THEN ISNULL (R.KAU, 0)
				END AS AP
			FROM dbo.ARestTableByDate (@dDATE_REST_E, @nSel_Spr1) R
			INNER JOIN @TAB_KBK KBK ON (KBK.LINK_KBK = ISNULL (R.KBK, 0))
			INNER JOIN dbo.S_ACCOUNTS SA ON (R.ACCOUNT = SA.LINK)
			WHERE R.DEP_LINK = @DEP_LINK
			GROUP BY S_ACTIVE, S_PASSIVE,
				CASE
					WHEN @strCODE_AP = 'EKR' THEN ISNULL (R.EKR, 0)
					WHEN @strCODE_AP = 'KAU' THEN ISNULL (R.KAU, 0)
				END
			) 
				AS R1 ON R1.AP = AP.LINK_AP
	END

	EXEC dbo.X_GET_TABLE_NAME @cCROSS_TABLE_DB OUTPUT
	EXEC dbo.X_GET_TABLE_NAME @cCROSS_TABLE_KT OUTPUT

	EXEC dbo.M_CROSS_TABLE 'DATE_OP, JO_NUM, NAME_OPER, REST_B, REST_E, DATE_E', 'AC', 'VARCHAR (60)', 'SS, RB, RE',
			'NUMERIC (28,4)#NUMERIC (28,4)#NUMERIC (28,4)', 'SUM (SS) AS SS, 0 AS RB, 0 AS RE',
			'#ACCT_IN_DB', @cCROSS_TABLE_DB

	EXEC dbo.M_CROSS_TABLE 'DATE_OP, JO_NUM, NAME_OPER, REST_B, REST_E, DATE_E', 'AC', 'VARCHAR (60)', 'SS, RB, RE',
			'NUMERIC (28,4)#NUMERIC (28,4)#NUMERIC (28,4)', 'SUM (SS) AS SS, 0 AS RB, 0 AS RE',
			'#ACCT_IN_KT', @cCROSS_TABLE_KT

	--- Готовим для вывода счет ДБ ---
	SET @intCOUNTER = (SELECT COUNT (DISTINCT AC) FROM #ACCT_IN_DB)
	SET @intCOUNTER = ISNULL (@intCOUNTER, 0)
	SET @intCOUNT_COLROW = @intCOUNTER

	WHILE @intCOUNTER < @intMAX_REC
	BEGIN
		SET @intCOUNTER = @intCOUNTER + 1
		SET @cCOUNTER = LTRIM (STR (@intCOUNTER))
		SET @cSQL_STR = 'ALTER TABLE ' + @cCROSS_TABLE_DB
			+ ' ADD AC_' + @cCOUNTER + ' VARCHAR (60) '
			+ ', SS_' + @cCOUNTER + ' [NUMERIC] (28,4)'
			+ ', RB_' + @cCOUNTER + ' [NUMERIC] (28,4)'
			+ ', RE_' + @cCOUNTER + ' [NUMERIC] (28,4)'
		EXECUTE (@cSQL_STR)
	END 

	SET @intCOUNTER = 0
	WHILE @intCOUNTER < @intCOUNT_COLROW
	BEGIN
		SET @intCOUNTER = @intCOUNTER + 1
		SET @cCOUNTER = LTRIM (STR (@intCOUNTER))
		SET @cSQL_STR = 'DECLARE @SUM_RB NUMERIC (28,4), @SUM_RE NUMERIC (28,4), @KEY_FIELD VARCHAR (20)' + CHAR (10)
			+ 'SET @KEY_FIELD = (SELECT TOP 1 AC_' + @cCOUNTER + ' FROM ' + @cCROSS_TABLE_DB + ')' + CHAR (10) 
			+ 'SET @SUM_RB = (SELECT TOP 1 RB FROM #ACCT_IN_DB WHERE AC =  @KEY_FIELD)' + CHAR (10)
			+ 'SET @SUM_RE = (SELECT TOP 1 RE FROM #ACCT_IN_DB WHERE AC =  @KEY_FIELD)' + CHAR (10)
			+ 'UPDATE ' + @cCROSS_TABLE_DB + ' SET RB_' + @cCOUNTER + ' = ISNULL (@SUM_RB, 0), RE_'
				+ @cCOUNTER + ' = ISNULL (@SUM_RE, 0)'
		EXECUTE (@cSQL_STR)
	END

	IF @intCOUNT_COLROW = 0
		EXEC ('INSERT INTO ' + @cCROSS_TABLE_DB + ' (NAME_OPER) VALUES ('''') ')

	--- Готовим для вывода КТ ---
	SET @intCOUNTER = (SELECT COUNT (DISTINCT AC) FROM #ACCT_IN_KT)
	SET @intCOUNTER = ISNULL (@intCOUNTER, 0)
	SET @intCOUNT_COLROW = @intCOUNTER
	WHILE @intCOUNTER < @intMAX_REC
	BEGIN
		SET @intCOUNTER = @intCOUNTER + 1
		SET @cCOUNTER = LTRIM (STR (@intCOUNTER))
		SET @cSQL_STR = 'ALTER TABLE ' + @cCROSS_TABLE_KT
			+ ' ADD AC_' + @cCOUNTER + ' VARCHAR (60) '
			+ ', SS_' + @cCOUNTER + ' [NUMERIC] (28,4)'
			+ ', RB_' + @cCOUNTER + ' [NUMERIC] (28,4)'
			+ ', RE_' + @cCOUNTER + ' [NUMERIC] (28,4)'
		EXECUTE (@cSQL_STR)
	END 

	SET @intCOUNTER = 0
	WHILE @intCOUNTER < @intCOUNT_COLROW
	BEGIN
		SET @intCOUNTER = @intCOUNTER + 1
		SET @cCOUNTER = LTRIM (STR (@intCOUNTER))
		SET @cSQL_STR = 'DECLARE @SUM_RB NUMERIC (28,4), @SUM_RE NUMERIC (28,4), @KEY_FIELD VARCHAR (20)' + CHAR (10)
			+ 'SET @KEY_FIELD = (SELECT TOP 1 AC_' + @cCOUNTER + ' FROM ' + @cCROSS_TABLE_KT + ')' + CHAR (10) 
			+ 'SET @SUM_RB = (SELECT TOP 1 RB' + ' FROM #ACCT_IN_KT WHERE AC =  @KEY_FIELD)' + CHAR (10)
			+ 'SET @SUM_RE = (SELECT TOP 1 RE' + ' FROM #ACCT_IN_KT WHERE AC =  @KEY_FIELD)' + CHAR (10)
--			+ 'IF @SUM_RB IS NOT NULL OR @SUM_RE IS NOT NULL' + CHAR(10)
			+ 'UPDATE ' + @cCROSS_TABLE_KT + ' SET RB_' + @cCOUNTER + ' = ISNULL (@SUM_RB, 0), RE_'
				+ @cCOUNTER + ' = ISNULL (@SUM_RE, 0)'
--PRINT (@cSQL_STR)
		EXECUTE (@cSQL_STR)
	END

	IF @intCOUNT_COLROW = 0
		EXEC ('INSERT INTO ' + @cCROSS_TABLE_KT + ' (NAME_OPER) VALUES ('''') ')

	SELECT LINK,
		CODE AS ACCT_CODE,
		[NAME] AS ACCT_NAME,
		ISNULL (@DEP_OKPO, '') AS DEP_OKPO,
		ISNULL (@DEP_NAME, '') AS DEP_NAME,
		ISNULL (@GLBUH_NAME, '') AS GLBUH_NAME
	FROM dbo.S_ACCOUNTS
	WHERE LINK = @nSel_Spr1

	EXEC ('SELECT CONVERT (VARCHAR (10), DATE_OP, 104) AS DATE_OP_C, * FROM ' + @cCROSS_TABLE_DB)
	EXEC ('SELECT CONVERT (VARCHAR (10), DATE_OP, 104) AS DATE_OP_C, * FROM ' + @cCROSS_TABLE_KT)

	DROP TABLE #ACCT_IN_DB
	DROP TABLE #ACCT_IN_KT
	EXEC ('DROP TABLE ' + @cCROSS_TABLE_DB)
	EXEC ('DROP TABLE ' + @cCROSS_TABLE_KT)
END







GO


GRANT EXECUTE ON dbo.[BK_REPORT_MANYGRAPH_CARD] 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


-- сумма премии на первый месяц
IF ISNULL((@dR1 + @dR2 + @dR3),0)> 0
	begin
		SET @QPREM_S1  = isnull(((@QPREM_SUMM / (@dR1 + @dR2 + @dR3)) * @dR1),0)
	end	
ELSE 
	BEGIN
		SET @QPREM_S1 = isnull((@QPREM_SUMM * @dR1) ,0) 
	END	
-- сумма премии на второй месяц
IF ISNULL((@dR1 + @dR2 + @dR3),0)> 0
	begin
		SET @QPREM_S2  = isnull(((@QPREM_SUMM / (@dR1 + @dR2 + @dR3)) * @dR2),0)	
	end	
ELSE 
	BEGIN
		SET @QPREM_S2 = isnull((@QPREM_SUMM * @dR2) ,0) 
	END	
-- сумма премии на третий месяц
IF ISNULL((@dR1 + @dR2 + @dR3),0)> 0
	begin
		SET @QPREM_S3  = isnull(((@QPREM_SUMM / (@dR1 + @dR2 + @dR3)) * @dR3),0)	
	end	
ELSE 
	BEGIN
		SET @QPREM_S3 = isnull((@QPREM_SUMM * @dR3) ,0) 
	END	
-- обновление таблицы - к суммам по последним трем месяцам, прибавляется разбитая квартальная премия 
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 AND ISNULL((@dR1 + @dR2 + @dR3) , 0) > 0 AND  ISNULL( (@SUMMA1 + @SUMMA2 + @SUMMA3),0) > 0 
	begin
		SET @SR_SUM_3MONTH  = (((@SUMMA1 + @SUMMA2 + @SUMMA3)/ (@dF1 + @dF2 + @dF3)) * (@dR1 + @dR2 + @dR3)) /3	
	end
else 
	BEGIN 
		IF ISNULL((@SUMMA1 + @SUMMA2 + @SUMMA3),0) > 0
			begin
				set @SR_SUM_3MONTH = (@SUMMA1 + @SUMMA2 + @SUMMA3) / 3 
			end	
		ELSE
			BEGIN  	
				set @SR_SUM_3MONTH = 0
			end	
	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.[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

/*дату начала и дату окончания периода обновим*/
SET @DateBegin = dbo.ConvertDMY2Date(1,1,@Year) 
SET @DateEND = dbo.ConvertDMY2Date(1,12,@Year)
SET @DateEnd 	= dbo.DateEndOfMonth(@DateEND)

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.[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.[BK_REPORT_BOOK_AMORT1]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_REPORT_BOOK_AMORT1]

GO


CREATE      PROCEDURE dbo.BK_REPORT_BOOK_AMORT1
	@varKSnMonth1		INT			,
	@varKScYear1		VARCHAR (4)		,
	@varKScVal1	char(1), @varKSnOtborLink1	int,
	@dDATE_BEGIN		DATETIME	= NULL,
	@dDATE_END		DATETIME	= NULL,
	@intREPORT_BY_PERIOD	TINYINT		= 0,
	@intNO_AMORT	INT,
	@intSVOD_ZB INT,
	@cVal_KBK char(1), @nOtborLinkKBK int,		-- Отбор КБК --
	@intGRP_KBK	INT = 0,
	@intAMORT_ONLY_PER	INT = 0
--
AS
BEGIN

/*
SELECT
	intNO_AMORT = @intNO_AMORT,
	intSVOD_ZB = @intSVOD_ZB,
	intGRP_KBK	= @intGRP_KBK,
	intAMORT_ONLY_PER	= @intAMORT_ONLY_PER

RETURN
*/
--select 'start', convert (varchar (100), getdate (), 121)

	DECLARE
		@varKSDATE_BEGIN	DATETIME,	
		@varKSDATE_END		DATETIME,	
		@varKSDATE_REST		DATETIME,	
		@varKSLINK_DEP		INT		,
		@varKScNEXT_PERIOD	VARCHAR (10),
		@varKScBEGIN_PERIOD	VARCHAR (10),
		@varKScOtborAccount	VARCHAR (100),

		@varKSMonth		VARCHAR (20),
		@varKSP_CODE		VARCHAR (20),
		@varKSDEP_CODE		VARCHAR (20),
		@varKSDEP_NAME		VARCHAR (254),
		@varKSDEP_OKPO		VARCHAR (20),
		@varKSEMP_CODE		VARCHAR (20),
		@strGLBUH		VARCHAR (100),
		@varKSnSel_Spr1		INT,
		@varKSEMP_NAME		VARCHAR (254),
		@strDATE_END_PERIOD	VARCHAR (10),
		@intDEP_LINK	INT

	IF @intREPORT_BY_PERIOD = 0
	BEGIN
		SET @varKSDATE_BEGIN = dbo.DateBeginOfMonth (dbo.ConvertDMY2Date (1, @varKSnMonth1, CONVERT (INT, @varKScYear1)))
		SET @varKSDATE_END = dbo.DateEndOfMonth (@varKSDATE_BEGIN)
	END
	ELSE
	BEGIN
		SET @varKSDATE_BEGIN = @dDATE_BEGIN
		SET @varKSDATE_END = @dDATE_END
	END

	SET @strDATE_END_PERIOD	= CONVERT (VARCHAR (10), @varKSDATE_END, 104)
	SET @intNO_AMORT = ISNULL (@intNO_AMORT, 0)
	SET @intDEP_LINK = dbo.BK_GetDepZB () 

	DECLARE @ACCT_BALANSE TABLE (LINK_ACCT [INT],
					cSOURCE CHAR (1),
					cSINTH CHAR (3),
					cANALIT CHAR (2),
					cUSER VARCHAR (4))

	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT_BALANSE
		SELECT RECORD,
			SA.cSOURCE,
			SA.cSINTH,
			SA.cANALIT,
			SA.cUSER
		FROM dbo.OBJECT_VAR_ACCT OV_AC
		INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OV_AC.RECORD)
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT_BALANSE
		SELECT T1.LINK,
			T1.cSOURCE,
			T1.cSINTH,
			T1.cANALIT,
			T1.cUSER
		FROM dbo.BK_GetAcctTableByCode ('101', DEFAULT, DEFAULT, DEFAULT) T1
		UNION ALL
		SELECT T1.LINK,
			T1.cSOURCE,
			T1.cSINTH,
			T1.cANALIT,
			T1.cUSER
		FROM dbo.BK_GetAcctTableByCode ('102', DEFAULT, DEFAULT, DEFAULT) T1
		UNION ALL
		SELECT T1.LINK,
			T1.cSOURCE,
			T1.cSINTH,
			T1.cANALIT,
			T1.cUSER
		FROM dbo.BK_GetAcctTableByCode ('108', '01,02,03', DEFAULT, DEFAULT) T1
		UNION ALL
		SELECT T1.LINK,
			T1.cSOURCE,
			T1.cSINTH,
			T1.cANALIT,
			T1.cUSER
		FROM dbo.BK_GetAcctTableByCode ('108', '51,52,54', DEFAULT, DEFAULT) T1

	DECLARE @ACCT_AMORT TABLE (LINK_ACCT [INT],
					cSOURCE CHAR (1),
					cSINTH CHAR (3),
					cANALIT CHAR (2),
					cUSER VARCHAR (4))

	INSERT INTO @ACCT_AMORT
	SELECT
		T1.LINK,
		T1.cSOURCE,
		T1.cSINTH,
		T1.cANALIT,
		T1.cUSER
	FROM dbo.BK_GetAcctTableByCode ('104', DEFAULT, DEFAULT, DEFAULT) T1

	--- Отбор КБК --- 
	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 = [NAME],
		@varKSDEP_OKPO = OKPO
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @varKSLINK_DEP

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

	SET @varKSDATE_REST = DATEADD (DAY, 1, @varKSDATE_END)

	DECLARE @BALANSE_OS TABLE (DEP [INT], ACCOUNT [INT], INV [INT], KBK INT,
		IN_QTY [NUMERIC] (28,4), IN_SUMMA [NUMERIC] (28,4),
		OUT_QTY [NUMERIC] (28,4), OUT_SUMMA [NUMERIC] (28,4))

	INSERT INTO @BALANSE_OS
	SELECT T1.DEP,
		T1.ACCOUNT,
		T1.INV,
		T1.KBK,
		SUM (T1.IN_QTY),
		SUM (T1.IN_SUMMA),
		SUM (T1.OUT_QTY),
		SUM (T1.OUT_SUMMA)
	FROM dbo.BK_GetTableOSVByDate (@varKSDATE_BEGIN, @varKSDATE_END, @intDEP_LINK) T1
	INNER JOIN @ACCT_BALANSE T2 ON (T2.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN @TAB_KBK T3 ON (T3.LINK_KBK = T1.KBK)
	WHERE @intSVOD_ZB = 1 
		OR (@intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSLINK_DEP)
	GROUP BY T1.DEP,
		T1.ACCOUNT,
		T1.INV,
		T1.KBK

--select '@BALANSE_OS', convert (varchar (100), getdate (), 121)


	DECLARE @AMORT_OS TABLE (ACCOUNT [INT], INV [INT], KBK INT, 
		cSOURCE CHAR (1), cSINTH CHAR (3), cANALIT CHAR (2), cUSER VARCHAR (4),
		IN_SUMMA [NUMERIC] (28,4), K_SUMMA [NUMERIC] (28,4),
		OUT_SUMMA [NUMERIC] (28,4))

	INSERT INTO @AMORT_OS
	SELECT T1.ACCOUNT,
		T1.INV,
		T1.KBK,
		T2.cSOURCE,
		T2.cSINTH,
		T2.cANALIT,
		T2.cUSER,
		SUM (ISNULL (T1.IN_SUMMA, 0)),
		SUM (ISNULL (T1.K_SUMMA, 0)),
		SUM (ISNULL (T1.OUT_SUMMA, 0))
	FROM dbo.BK_GetTableOSVByDate (@varKSDATE_BEGIN, @varKSDATE_END, @intDEP_LINK) T1
	INNER JOIN @ACCT_AMORT T2 ON (T2.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN @TAB_KBK T3 ON (T3.LINK_KBK = T1.KBK)
--	WHERE T1.DEP_LINK = @varKSLINK_DEP
	WHERE @intSVOD_ZB = 1 
		OR (@intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSLINK_DEP)
	GROUP BY T1.ACCOUNT,
		T1.INV,
		T1.KBK,
		T2.cSOURCE,
		T2.cSINTH,
		T2.cANALIT,
		T2.cUSER
	HAVING	SUM (ISNULL (T1.IN_SUMMA, 0)) <> 0
		OR SUM (ISNULL (T1.K_SUMMA, 0)) <> 0
		OR SUM (ISNULL (T1.OUT_SUMMA, 0)) <> 0

--select '@AMORT_OS', convert (varchar (100), getdate (), 121)

	DECLARE @TABLE_DATE_OUT_OS TABLE (INV [INT], DATE_OUT [DATETIME])
	INSERT INTO @TABLE_DATE_OUT_OS
	SELECT INV,
		MAX (DATE_OPER)
	FROM dbo.BK_GetDateTableOutOS (DEFAULT , @varKSDATE_END)
	GROUP BY INV

--select '@TABLE_DATE_OUT_OS', convert (varchar (100), getdate (), 121)

	-- ОС, по которым начислялась амортизация за указанный период --
	SET @intAMORT_ONLY_PER = ISNULL (@intAMORT_ONLY_PER, 0)
--SELECT @varKSDATE_END,  * FROM @TABLE_DATE_OUT_OS

	DECLARE
		@TAB_RES TABLE (ACCOUNT [INT], INV [INT],
		ACCT_CODE [VARCHAR] (30),
		INV_CODE [VARCHAR] (20), INV_NAME [VARCHAR] (254),
		BEGIN_USED [VARCHAR] (10), 
		QTY [NUMERIC] (28,4), BALANSE [NUMERIC] (28,4),
		ASUM_PB [NUMERIC] (28,4), ASUM_P [NUMERIC] (28,4), ASUM_PE [NUMERIC] (28,4),
		LSUM_BE  [NUMERIC] (28,4), LSUM_PE  [NUMERIC] (28,4),
		PERC_RATE [NUMERIC] (10,2),
		DEP_NAME [VARCHAR] (254),
		GLBUH [VARCHAR] (100),
		MONTH_NAME [VARCHAR] (20),
		YEAR_NAME [INT],
		DATE1 [VARCHAR] (10),
		DATE2 [VARCHAR] (10),
		YPERC_RATE [FLOAT],
		YSUM_RATE  [NUMERIC] (28,4),
		MSUM_RATE  [NUMERIC] (28,4),
		ISPERIOD   [TINYINT],
		PERIOD_END [VARCHAR] (10),
		DATE_OUT [VARCHAR] (10),
		KBK_CODE VARCHAR (30))

	SET @varKSMonth = dbo.DateMonthName (@varKSnMonth1)
	SET @varKSMonth = ISNULL (@varKSMonth, '')

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

	SET @intGRP_KBK = ISNULL (@intGRP_KBK, 0)


	INSERT INTO @TAB_RES
	SELECT
		T1.ACCOUNT,
		T1.INV,
		RTRIM (SA.CODE),
		ISNULL (INV.CODE, ''),
		ISNULL (INV.NAME, ''),
		ISNULL (CONVERT (VARCHAR (10), INV_DOP.DATE_BEGIN, 104), ''),
		CASE
			WHEN T1.OUT_QTY > 0 THEN T1.OUT_QTY
			WHEN T1.IN_QTY > 0 THEN T1.IN_QTY
			ELSE 0
		END,
		CASE
			WHEN T1.OUT_SUMMA > 0 THEN T1.OUT_SUMMA
			WHEN T1.IN_SUMMA > 0 THEN T1.IN_SUMMA
			ELSE 0
		END,
		ISNULL (T2.IN_SUMMA, 0),
		ISNULL (T2.K_SUMMA, 0),
		ISNULL (T2.OUT_SUMMA, 0),
		T1.IN_SUMMA - ISNULL (T2.IN_SUMMA, 0),
		T1.OUT_SUMMA - ISNULL (T2.OUT_SUMMA, 0),
		0,
		@varKSDEP_NAME,
		@strGLBUH,
		@varKSMonth,
		YEAR (@varKSDATE_BEGIN),
		CONVERT (VARCHAR (10), @varKSDATE_BEGIN, 104),
		CONVERT (VARCHAR (10), DATEADD (DAY, 1, @varKSDATE_END), 104),
/*		ISNULL (INV_DOP.DEPRE_RATE, CASE
						WHEN ISNULL (INV_DOP.PERIOD_USED, 0) <> 0
						THEN 100 / INV_DOP.PERIOD_USED
						ELSE 0
					END),
*/		ISNULL (NORM_D.DEPRE_RATE, 0),
		0, 0,
		@intREPORT_BY_PERIOD,
		@strDATE_END_PERIOD,
		ISNULL (CONVERT (VARCHAR (10), DATE_OUT, 104), ''),
		ISNULL (K.CODE, '')
	FROM @BALANSE_OS T1
--	INNER JOIN @AMORT_OS T2 ON (T2.INV = T1.INV)
	INNER JOIN dbo.INVENTORY_CARD INV ON (INV.LINK = T1.INV)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = T1.ACCOUNT)
	LEFT OUTER JOIN @AMORT_OS T2 ON (T2.INV = T1.INV
				 AND T2.cSOURCE = SA.cSOURCE)
	LEFT OUTER JOIN dbo.BV_INVENTORY_CARD_DOP INV_DOP ON (INV_DOP.LINK_UP = T1.INV)
	LEFT OUTER JOIN @TABLE_DATE_OUT_OS OUT_OS ON (OUT_OS.INV = T1.INV)
	LEFT OUTER JOIN dbo.BK_GetNormDepreTableByOS (DEFAULT) NORM_D ON (NORM_D.INV = T1.INV)
	LEFT JOIN dbo.KL_KBK K ON (@intGRP_KBK = 1 AND K.LINK = T1.KBK)
	WHERE 
		(@intAMORT_ONLY_PER = 0 
			OR @intAMORT_ONLY_PER = 1 AND ISNULL (T2.K_SUMMA, 0) <> 0)
		AND (@intNO_AMORT = 0 AND T2.INV = T1.INV
			OR @intNO_AMORT = 1)


	UPDATE @TAB_RES SET PERC_RATE = ASUM_PE / BALANSE * 100
	WHERE BALANSE <> 0
	
	UPDATE @TAB_RES SET YSUM_RATE = BALANSE * YPERC_RATE /100
	UPDATE @TAB_RES SET MSUM_RATE = YSUM_RATE / 12

--select '@TAB_RES', convert (varchar (100), getdate (), 121)				

	SELECT * FROM @TAB_RES ORDER BY KBK_CODE, ACCT_CODE, RIGHT ('00000000000000000000' + INV_CODE, 20)

--select 'end', convert (varchar (100), getdate (), 121)
	
END






GO


GRANT EXECUTE ON dbo.[BK_REPORT_BOOK_AMORT1] TO PUBLIC

GO



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

GO

CREATE    PROC  dbo.RI_OSV_S4ET
	@dDate1	datetime,
	@dDate2 datetime,
	@intACCT	INT,
	@cVal1 char(1), @nOtborLink1 int	/*Фильтр ВКР*/,
	@cVal2 char(1), @nOtborLink2 int	/* фильтр ЭКР*/,
	@cVal3 char(1), @nOtborLink3 int	/*фильтр КАУ*/,
	@cVal4 char(1), @nOtborLink4 int	/*фильтр Доп.кл-ция */,
	@strAP_CODE	VARCHAR (60) = '',
	@intACCT_GRP	INT,
	@intSVOD_ZB	INT	
AS
BEGIN

	DECLARE @cSel_Spr1 varchar(4000),
		@strTITLE_AP	VARCHAR (20),
		@strACCT_CODE	VARCHAR (20),

		@varKSLINK_DEP	INT,
		@varKSDEP_NAME	VARCHAR (254)

	SELECT @strTITLE_AP = S_TITLE FROM dbo.ANALIT WHERE CODE_AP = @strAP_CODE
	SET @strTITLE_AP = ISNULL (@strTITLE_AP, '')

	SELECT @strACCT_CODE = CODE FROM dbo.S_ACCOUNTS WHERE LINK = @intACCT

	declare @KBK table (link int, code varchar (30))
	declare @EKR table (link int, code varchar (30))

	--- Выборка счетов ---
	DECLARE @TABLE_ACCT TABLE (LINK INT)
	INSERT INTO @TABLE_ACCT
	SELECT LINK
	FROM dbo.AccountsSubtreeByRoot (@intACCT)

	if LEN(@cVal1) > 0
		insert @KBK
		SELECT OVR.RECORD,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLink1
	else 
		insert @KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	if LEN(@cVal2) > 0
		insert @EKR
		SELECT OVR.RECORD, D.CODE
		FROM dbo.OBJECT_VAR_KOSGU OVR, dbo.KOSGU D
		WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP = @nOtborLink2
	else 
		insert @EKR
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('EKR')

	--- Показатель ---
	DECLARE @TABLE_AP TABLE (LINK INT, CODE VARCHAR (30),
		AP_NAME VARCHAR (254))

	IF @strAP_CODE = 'KAU'
		if LEN(@cVal3) > 0
			insert @TABLE_AP
			SELECT OVR.RECORD, D.CODE, ''
			FROM dbo.OBJECT_VAR_KAU OVR, dbo.DICTIONARY_ANALYTICAL_CODES D
			WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@nOtborLink3
		else
			insert @TABLE_AP
			SELECT LINK_AP, AP_CODE, ''
			FROM dbo.BK_GetTableDictionByAP ('KAU')	

	IF @strAP_CODE = 'AP2'
		if LEN(@cVal4) > 0
			insert @TABLE_AP
			SELECT OVR.RECORD, D.AP_CODE, ''
			FROM dbo.OBJECT_VAR_DOP_CLASSIF OVR, dbo.BK_GetTableDictionByAP ('AP2') D
			WHERE D.LINK_AP = OVR.RECORD AND OVR.LINK_UP=@nOtborLink4
		else
			insert @TABLE_AP
			SELECT LINK_AP, AP_CODE, ''
			FROM dbo.BK_GetTableDictionByAP ('AP2')	

	IF @strAP_CODE = 'DEP' OR @strAP_CODE = 'EMP'
		INSERT @TABLE_AP
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP (@strAP_CODE)	

	IF ISNULL (@strAP_CODE, '') = ''
		INSERT INTO @TABLE_AP
		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 @varKSDEP_NAME = dbo.BK_GET_PRINT_DEP_NAME (LINK)
		+ CASE
			WHEN @intSVOD_ZB = 1 THEN ' (ЦБ)'
			ELSE ''
		END	
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @varKSLINK_DEP

	IF @intSVOD_ZB = 1 
		SET @varKSLINK_DEP = NULL

	--- ОСВ ---
	DECLARE @TABLE_OSV TABLE
		(ACCOUNT INT,
		KBK INT,
		EKR INT,
		AP INT,
		DIN_SUM NUMERIC (20,2),
		KIN_SUM NUMERIC (20,2),
		D_SUM NUMERIC (20,2),
		K_SUM NUMERIC (20,2),
		DOUT_SUM NUMERIC (20,2),
		KOUT_SUM NUMERIC (20,2))

	SET @intACCT_GRP = ISNULL (@intACCT_GRP, 0)

	INSERT INTO @TABLE_OSV
	SELECT CASE
			WHEN @intACCT_GRP = 1 THEN OSV.ACCOUNT
			ELSE 0
		END,
		OSV.KBK, OSV.EKR,
		CASE 
			WHEN @strAP_CODE = 'KAU' THEN OSV.KAU
			WHEN @strAP_CODE = 'AP2' THEN OSV.AP2
			WHEN @strAP_CODE = 'DEP' THEN OSV.DEP
			WHEN @strAP_CODE = 'EMP' THEN OSV.EMP
			ELSE 0
		END AS AP,
		CASE WHEN SA_ACTIVE = 1 THEN SUM (IN_SUMMA) ELSE 0 END AS DIN_SUM,
		CASE WHEN SA_PASSIVE = 1 THEN SUM (IN_SUMMA) ELSE 0 END AS KIN_SUM,
		SUM (D_SUMMA) AS D_SUM, SUM (K_SUMMA) AS K_SUM,
		CASE WHEN SA_ACTIVE = 1 THEN SUM (OUT_SUMMA) ELSE 0 END AS DOUT_SUM,
		CASE WHEN SA_PASSIVE = 1 THEN SUM (OUT_SUMMA) ELSE 0 END AS KOUT_SUM
	FROM dbo.BK_GetTableOSVByDate (@dDate1, @dDate2, @varKSLINK_DEP) OSV
	INNER JOIN @TABLE_ACCT AC ON (AC.LINK = OSV.ACCOUNT)
	GROUP BY
		CASE
			WHEN @intACCT_GRP = 1 THEN OSV.ACCOUNT
			ELSE 0
		END,
		OSV.KBK, OSV.EKR,
			CASE 
				WHEN @strAP_CODE = 'KAU' THEN OSV.KAU
				WHEN @strAP_CODE = 'AP2' THEN OSV.AP2
				WHEN @strAP_CODE = 'DEP' THEN OSV.DEP
				WHEN @strAP_CODE = 'EMP' THEN OSV.EMP
				ELSE 0
			END, SA_ACTIVE, SA_PASSIVE
	HAVING SUM (IN_SUMMA) <> 0
		OR SUM (D_SUMMA) <> 0 OR SUM (K_SUMMA) <> 0
		OR SUM (OUT_SUMMA) <> 0



	-- РЕЗУЛЬТАТ --
	DECLARE @TABLE_RES TABLE
		(ACCT_GR VARCHAR (20),
		COL1 VARCHAR (30), --* КБК *--
		COL2 VARCHAR (30), -- ЭКР 
		COL3 VARCHAR (254), -- Показатель --
		COL4 NUMERIC (20,2), -- Сальдо на начало периода - дебет --
		COL5 NUMERIC (20,2), -- Сальдо на начало периода - кредит --
		COL6 NUMERIC (20,2), -- Обороты за период - дебет --
		COL7 NUMERIC (20,2), -- Обороты за период - кредит --
		COL8 NUMERIC (20,2), -- Сальдо на конец период - дебет --
		COL9 NUMERIC (20,2) -- Сальдо на конец период - кредит --
		)

	INSERT INTO @TABLE_RES
	SELECT ISNULL (SA.CODE, ''),
		V.CODE, --* КБК *--
		E.CODE, -- ЭКР 
		CASE
			WHEN @strAP_CODE = 'KAU' OR @strAP_CODE = 'AP2' THEN AP.CODE
			ELSE AP.AP_NAME
		END, -- Показатель --
		DIN_SUM,
		KIN_SUM,
		D_SUM,
		K_SUM,
		DOUT_SUM,
		KOUT_SUM 
	FROM @TABLE_OSV OSV
	INNER JOIN @KBK V ON (V.LINK = OSV.KBK)
	INNER JOIN @EKR E ON (E.LINK = OSV.EKR)
	INNER JOIN @TABLE_AP AP ON (AP.LINK = OSV.AP)
	LEFT JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.ACCOUNT)

	SELECT *,
		@strTITLE_AP AS COL3_NAME,
		@strACCT_CODE AS ACCT_CODE,
		@varKSDEP_NAME AS DEP_NAME
	FROM @TABLE_RES
	ORDER BY ACCT_GR, COL1, COL2, COL3

END


GO


GRANT EXECUTE ON dbo.[RI_OSV_S4ET] 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

SELECT @LinkEKR211 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '211'
SELECT @LinkEKR213 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '213'

/* Для штатников, кроме НДФЛ и ЕСН*/
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 WHEN P.WAY_CALC = 13 THEN (CASE WHEN JC.LINK_EKR = @LinkEKR213 THEN P.LINK_OPER ELSE P.LINK_OPER3 END) ELSE P.LINK_OPER END),
		 [REF_ORG] = JC.LINK_ORG,
		 [REF_BUD] = JC.LINK_VKR,
		 [REF_EKR] = JC.LINK_EKR
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
					-- проверим если ли в счете код источника финансирования, если нет - добавим
					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.[RJ_AUTOFILL_2MS_2016]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RJ_AUTOFILL_2MS_2016]

GO

/*
© Кейсистемс (Keysystems), 2008 
*/
CREATE PROCEDURE dbo.[RJ_AUTOFILL_2MS_2016]
	@varKSsFLink	int			-- экземпляр формы, для которой используется автозаполнение
AS
--//--

declare @link_form int
declare @date_begin datetime			-- дата формирования
declare @link_table int				-- ссылка на талицу
declare @link_col int				-- ссылка на колонку
declare @link_row int				-- ссылка на строку
--
--перенос формы из архивной базы
exec RN_MOVE_FORM_FROM_ARH @varKSsFLink


delete from report_summa where link_saved_form = @varKSsFLink
--
select @link_form = link_form, @date_begin = dbo.DateEndOfMonth(begin_date) from report_saved_forms where link_saved_form = @varKSsFLink
-----------------------------------
-- таблица всех сотрудников
select	[LINK] = 	 EM_PL.LINK,							-- ССЫЛКА НА СОТРУДНИКА
	[PERS_LINK] = 	 EM_PL.PERS_LINK,						-- ССЫЛКА НА СОТРУДНИКА
	[GOSSL] = 	 ST.GOSSL,							-- ТИП ДОЛЖНОСТИ (3- МУН.СЛУЖБЫ, 4- МУН.)
	[KAT_GOS_CODE] = ST.kat_gos_CODE,						-- КАТЕГОРИЯ ДОЛЖНОСТИ (1- рук, 2- помощ, 3- спец, 4- об.спец)
	[GR_GOS_CODE] =  ST.gr_gos_CODE,						-- ГРУППА ДОЛЖНОСТИ (1- высш, 2- глав, 3- вед, 4-с тар, 5- млад)
	[SEX] = 	 P.SEX,								-- ПОЛ (1- муж, 2- жен)
	-- ДАННЫЕ ДЛЯ УСЛОВИЙ ВЫБОРКИ СОТРУДНИКОВ
	[NOTWORK] =	EM_PL.NOTWORK,
	[NEW_FACE] =	IM.NEW_FACE,
	[TYPE_MOVE] = 	IM.TYPE,
	[TEMP_LINK] =	IM.TEMP_LINK,
	[DATE_END2] = 	IM.DATE_END2
into	#EMPLS_INFO
from	KU_EMPL_PLACING_FN(@date_begin) EM_PL left join DICTIONARY_STAFF_FN(@date_begin) ST
	on EM_PL.STAFF_LINK = ST.STAFF_LINK LEFT JOIN PERSON P
	on EM_PL.PERS_LINK = P.LINK LEFT JOIN ITEM_MOVE IM
	on EM_PL.ITEM_MOVE_LINK = IM.LINK
where	EM_PL.dep_link = (select dep_link from USER_DEP)				-- СОТРУДНИКИ ТОЛЬКО ТЕКУЩЕЙ ОРГАНИЗАЦИИ
	and EM_PL.sack = 0								-- ТОЛЬКО РАБОТАЮЩИЕ (ИСКЛЮЧАЕМ УВОЛЕННЫХ)
	and isnull(EM_PL.DATE_BEGIN,0) != 0						-- ГАРАНТИРОВАННО ПРИНЯТЫХ (ИСКЛЮЧАЕМ ТЕХ, КТО ВИСИТ В ПРОЕКТАХ ПРИКАЗАХ)
	and ST.GOSSL in (3,4)

DELETE FROM #EMPLS_INFO WHERE ISNULL(GR_GOS_CODE,0) = 0

DECLARE	@SQL_STR VARCHAR(2000)
DECLARE @OPT INT
SET @OPT = dbo.sa_get_option_by_code('KADRY_OPT4')
SET @SQL_STR =	CASE WHEN @OPT = 2 THEN							-- ИСКЛЮЧАЕМ ВРЕМЕННЫХ СОТРУДНКИОВ
			'
			DELETE	FROM #EMPLS_INFO 					
			WHERE	NOTWORK = 1
			'
		     WHEN @OPT = 1 THEN							-- ИСКЛЮЧАЕМ ВРЕМЕННО НЕ РАБОТЮЩИХ ОСНОВНЫХ СОТРУДНИКОВ
			'
			DELETE	FROM #EMPLS_INFO
			WHERE	(NEW_FACE = 1 AND ISNULL(TEMP_LINK,0) != 0)					-- если временно приняты вместо кого-то
				OR (NEW_FACE = 1 AND ISNULL(DATE_END2,''99991231'') != ''99991231'') 		-- если просто приняты временнно
				OR (NEW_FACE = 0 AND TYPE_MOVE = 1)						-- если перведены временно
			'	
		END
EXEC(@SQL_STR)
-----------------------------------
-- таблица всех курсов повышений квалификаций в отчетном году
SELECT	[EMPL] = 	EI.EMPL_LINK,				-- ссылка на сотрудника
	[DATE] = 	EI.DATE_END,				-- дата окончания
	[DIR] = 	EI.DIRECTION,				-- направление
								--		1) урпавленческое
								--		2) правовое
								--		3) организационно-экономическое
								--		4) планово-финансовое
								--		5) информационно-аналитическое
								--		6) другое
	[TIME] = 	EI.TIME,				-- количество часов
	[FORM] = 	EI.FORM_EDUC,				-- форма обучения
								--		1) с отрывом от службы
								--		2) без отрыва от службы
								--		3) частично
	[GOS] = 	CASE WHEN S.GOS_FLAG = 1 THEN 1		-- тип вуза
			     ELSE 2				--		1) государственный
			END,					--		2) негосударственный
	[FIN] = 	EI.FIN_SOURCE				-- источник финансирования обучения
								--		1) федеральный бюджет
								--		2) федеральный бюджет (гос.закакз)
								--		3) бюджет субъекта РФ
								--		4) бюджет субъекта РФ (гос.заказ)
								--		5) муниципальный бюджет
								--		6) муниципальный бюджет (мун.заказ)
								--		7) средства международных органов и организаций
								--		8) средства самого служащего
								--		9) иные источники финансирования
INTO	#EMPL_INCQUAL
FROM	EMPL_INCQUAL EI LEFT JOIN SCHOOL S ON EI.SCHOOL_LINK = S.LINK
WHERE	YEAR(EI.DATE_END) = YEAR(@date_begin)			-- ТОЛЬКО ПРОШЕДШИЕ ЗА ТЕКУЩИЙ ГОД
	AND EI.DATE_END <= @date_begin				-- ТОЛЬКО ПРОШЕДШИЕ ДО ТЕКУЩЕЙ ДАТЫ
-----------------------------------
-- таблица всех профессиональных переподготовок в отчетном году
SELECT	[EMPL] = 	EP.EMPL_LINK,				-- ссылка на сотрудника
	[DATE] = 	EP.DATE_END,				-- дата окончания
	[DIR] = 	EP.DIRECTION,				-- направление
								--		1) урпавленческое
								--		2) правовое
								--		3) организационно-экономическое
								--		4) планово-финансовое
								--		5) информационно-аналитическое
								--		6) другое
	[TIME] = 	EP.TIME,				-- количество часов
	[FORM] = 	EP.FORM_EDUC,				-- форма обучения
								--		1) с отрывом от службы
								--		2) без отрыва от службы
								--		3) частично
	[GOS] = 	S.GOS_FLAG,				-- тип вуза
								--		1) государственный
								--		2) негосударственный
	[FIN] = 	EP.FIN_SOURCE				-- источник финансирования обучения
								--		1) федеральный бюджет
								--		2) федеральный бюджет (гос.закакз)
								--		3) бюджет субъекта РФ
								--		4) бюджет субъекта РФ (гос.заказ)
								--		5) муниципальный бюджет
								--		6) муниципальный бюджет (мун.заказ)
								--		7) средства международных органов и организаций
								--		8) средства самого служащего
								--		9) иные источники финансирования
INTO	#EMPL_PROFP
FROM	EMPL_PROFP EP LEFT JOIN SCHOOL S ON EP.SCHOOL_LINK = S.LINK
WHERE	YEAR(EP.DATE_END) = YEAR(@date_begin)			-- ТОЛЬКО ПРОШЕДШИЕ ЗА ТЕКУЩИЙ ГОД
	AND EP.DATE_END <= @date_begin				-- ТОЛЬКО ПРОШЕДШИЕ ДО ТЕКУЩЕЙ ДАТЫ

--*******************************--
--********** РАЗДЕЛ 1 ***********--
--*******************************--
-- выбор таблицы
select @link_table = link_table from report_tables where link_form = @link_form and orders = 1
-- заполнение данных
-- **************************************************************
-- ***********************   3 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 3
-- 101
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 4)
-- 103
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 3 AND GR_GOS_CODE = 1)
-- 104
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 3 AND GR_GOS_CODE = 2)
-- 105
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 3 AND GR_GOS_CODE = 3)
-- 106
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 3 AND GR_GOS_CODE = 4)
-- 107
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL = 3 AND GR_GOS_CODE = 5)
-- 110
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL IN (3,4) AND SEX = 2)
-- 111
select @link_row = link_row from report_rows where link_table = @link_table and orders = 11
	insert into report_summa
	select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO where GOSSL IN (3,4) AND SEX = 1)
-- **************************************************************
-- ***********************   5 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 5
-- 101
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 4 AND ISNULL(EP.EMPL,0) != 0)
-- 103
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND ISNULL(EP.EMPL,0) != 0)
-- 104
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND ISNULL(EP.EMPL,0) != 0)
-- 105
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND ISNULL(EP.EMPL,0) != 0)
-- 106
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND ISNULL(EP.EMPL,0) != 0)
-- 107
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND ISNULL(EP.EMPL,0) != 0)
-- 110
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL IN (3,4) AND E.SEX = 2 AND ISNULL(EP.EMPL,0) != 0)
-- 111
select @link_row = link_row from report_rows where link_table = @link_table and orders = 11
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL IN (3,4) AND E.SEX = 1 AND ISNULL(EP.EMPL,0) != 0)

-- **************************************************************
-- ***********************   6 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 6
-- 101
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 4 AND ISNULL(EI.EMPL,0) != 0)
-- 103
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND ISNULL(EI.EMPL,0) != 0)
-- 104
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND ISNULL(EI.EMPL,0) != 0)
-- 105
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND ISNULL(EI.EMPL,0) != 0)
-- 106
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND ISNULL(EI.EMPL,0) != 0)
-- 107
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND ISNULL(EI.EMPL,0) != 0)
-- 110
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL IN (3,4) AND E.SEX = 2 AND ISNULL(EI.EMPL,0) != 0)
-- 111
select @link_row = link_row from report_rows where link_table = @link_table and orders = 11
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL IN (3,4) AND E.SEX = 1 AND ISNULL(EI.EMPL,0) != 0)
-- **************************************************************
-- ***********************  10 КОЛОНКА **************************
-- **************************************************************
/*select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 10
-- 101
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 4 AND ISNULL(EP.EMPL,0) != 0 AND FIN = 6)
-- 103
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND ISNULL(EP.EMPL,0) != 0 AND FIN = 6)
-- 104
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND ISNULL(EP.EMPL,0) != 0 AND FIN = 6)
-- 105
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND ISNULL(EP.EMPL,0) != 0 AND FIN = 6)
-- 106
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND ISNULL(EP.EMPL,0) != 0 AND FIN = 6)
-- 107
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND ISNULL(EP.EMPL,0) != 0 AND FIN = 6)
-- 110
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL IN (3,4) AND E.SEX = 2 AND ISNULL(EP.EMPL,0) != 0 AND FIN = 6)
-- 111
select @link_row = link_row from report_rows where link_table = @link_table and orders = 11
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL IN (3,4) AND E.SEX = 1 AND ISNULL(EP.EMPL,0) != 0 AND FIN = 6)


-- **************************************************************
-- ***********************  11 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 11
-- 101
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 4 AND ISNULL(EI.EMPL,0) != 0 AND FIN = 6)
-- 103
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND ISNULL(EI.EMPL,0) != 0 AND FIN = 6)
-- 104
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND ISNULL(EI.EMPL,0) != 0 AND FIN = 6)
-- 105
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND ISNULL(EI.EMPL,0) != 0 AND FIN = 6)
-- 106
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI. EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND ISNULL(EI.EMPL,0) != 0 AND FIN = 6)
-- 107
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND ISNULL(EI.EMPL,0) != 0 AND FIN = 6)
-- 110
select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL IN (3,4) AND E.SEX = 2 AND ISNULL(EI.EMPL,0) != 0 AND FIN = 6)
-- 111
select @link_row = link_row from report_rows where link_table = @link_table and orders = 11
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL IN (3,4) AND E.SEX = 1 AND ISNULL(EI.EMPL,0) != 0 AND FIN = 6)
*/--************************************************--
--********** СПРАВКА 1 И 2 К РАЗДЕЛУ 1 ***********--
--************************************************--
-- выбор таблицы
select @link_table = link_table from report_tables where link_form = @link_form and orders = 2
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 3
-----------------------------------------------------------------------------------------
--------------------------- СПРАВКА 1 -----------------------------------------------------
-------------------------------------------------------------------------------------------
CREATE TABLE #TEMP(EMPL INT)
-------------------------------------------------------------------------------------------
-- 132
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL_LINK FROM EMPL_ATTEST
WHERE YEAR(DATE) = YEAR(@date_begin) AND DATE <= @date_begin AND EMPL_LINK IN (SELECT LINK FROM #EMPLS_INFO WHERE GOSSL = 3)
	AND RTRIM(LTRIM((SELECT TOP 1 NAME FROM DICTIONARY_ATT_RESH_COM WHERE LINK = ATT_LINK))) LIKE 'соотв%'

select @link_row = link_row from report_rows where link_table = @link_table and orders = 2
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 133
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
-- 134
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
-- 135
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL_LINK FROM EMPL_ATTEST
WHERE YEAR(DATE) = YEAR(@date_begin) AND DATE <= @date_begin AND EMPL_LINK IN (SELECT LINK FROM #EMPLS_INFO WHERE GOSSL = 3)
	AND RTRIM(LTRIM((SELECT TOP 1 NAME FROM DICTIONARY_ATT_RESH_COM WHERE LINK = ATT_LINK))) LIKE 'не соотв%'

select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 136
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL_LINK FROM EMPL_RESERV
WHERE YEAR(DATE) = YEAR(@date_begin) AND DATE <= @date_begin AND EMPL_LINK IN (SELECT LINK FROM #EMPLS_INFO WHERE GOSSL = 3)

select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 137
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
-- 138
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL_LINK FROM EMPL_CHIN
WHERE YEAR(DATE) = YEAR(@date_begin) AND DATE <= @date_begin AND EMPL_LINK IN (SELECT LINK FROM #EMPLS_INFO WHERE GOSSL = 3)

select @link_row = link_row from report_rows where link_table = @link_table and orders = 8
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 139
select @link_row = link_row from report_rows where link_table = @link_table and orders = 9
-- 140
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL_LINK FROM ITEM_PENALTY
WHERE ACTIVE = 1 AND YEAR(PEN_DATE) = YEAR(@date_begin) AND PEN_DATE <= @date_begin AND EMPL_LINK IN (SELECT LINK FROM #EMPLS_INFO WHERE GOSSL = 3)

select @link_row = link_row from report_rows where link_table = @link_table and orders = 10
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 141
DELETE FROM #TEMP
INSERT #TEMP
SELECT EMPL_LINK FROM ITEM_MOVE 
WHERE NEW_FACE = 1 AND ACTIVE = 1 AND YEAR(DATE_BEGIN) = YEAR(@date_begin) AND DATE_BEGIN <= @date_begin
	AND ORDER_LINK IN (SELECT LINK FROM ORDERS WHERE DEP_LINK = (SELECT DEP_LINK FROM USER_DEP))

select @link_row = link_row from report_rows where link_table = @link_table and orders = 11
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 142
DELETE FROM #TEMP
INSERT #TEMP
SELECT EMPL_LINK FROM ITEM_MOVE
WHERE NEW_FACE = 1 AND ACTIVE = 1 AND YEAR(DATE_BEGIN) = YEAR(@date_begin) AND DATE_BEGIN <= @date_begin AND RTRIM(LTRIM(USL_PR)) LIKE '%конкурс%'
	AND ORDER_LINK IN (SELECT LINK FROM ORDERS WHERE DEP_LINK = (SELECT DEP_LINK FROM USER_DEP))

select @link_row = link_row from report_rows where link_table = @link_table and orders = 12
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 143
DELETE FROM #TEMP
INSERT #TEMP
SELECT EMPL_LINK FROM ITEM_MOVE
WHERE NEW_FACE = 1 AND ACTIVE = 1 AND YEAR(DATE_BEGIN) = YEAR(@date_begin) AND DATE_BEGIN <= @date_begin AND RTRIM(LTRIM(USL_PR)) LIKE '%резерв%'
	AND ORDER_LINK IN (SELECT LINK FROM ORDERS WHERE DEP_LINK = (SELECT DEP_LINK FROM USER_DEP))

select @link_row = link_row from report_rows where link_table = @link_table and orders = 13
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 144
DELETE FROM #TEMP
INSERT #TEMP
SELECT EMPL_LINK FROM ITEM_MOVE
WHERE NEW_FACE = 1 AND ACTIVE = 1 AND YEAR(DATE_BEGIN) = YEAR(@date_begin) AND DATE_BEGIN <= @date_begin AND (ISNULL(DATE_END2,'99991231') != '99991231' OR ISNULL(TEMP_LINK,0) = 1)
	AND ORDER_LINK IN (SELECT LINK FROM ORDERS WHERE DEP_LINK = (SELECT DEP_LINK FROM USER_DEP))

select @link_row = link_row from report_rows where link_table = @link_table and orders = 14
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 145
DELETE FROM #TEMP
INSERT #TEMP
SELECT EMPL_LINK FROM ITEM_DIS_FACE WHERE ACTIVE = 1 AND YEAR(DIS_DATE) = YEAR(@date_begin) AND DIS_DATE <= @date_begin
	AND ORDER_LINK IN (SELECT LINK FROM ORDERS WHERE DEP_LINK = (SELECT DEP_LINK FROM USER_DEP))

select @link_row = link_row from report_rows where link_table = @link_table and orders = 15
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 146
DELETE FROM #TEMP
INSERT #TEMP
SELECT EMPL_LINK FROM ITEM_DIS_FACE DF LEFT JOIN DICTIONARY_PUV P ON DF.REASON = P. LINK
WHERE ACTIVE = 1 AND YEAR(DIS_DATE) = YEAR(@date_begin) AND DIS_DATE <= @date_begin AND RTRIM(LTRIM(CODE)) = '0300'
	AND ORDER_LINK IN (SELECT LINK FROM ORDERS WHERE DEP_LINK = (SELECT DEP_LINK FROM USER_DEP))

select @link_row = link_row from report_rows where link_table = @link_table and orders = 16
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(SELECT COUNT(*) FROM #TEMP)
-- 147
select @link_row = link_row from report_rows where link_table = @link_table and orders = 17
-------------------------------------------------------------------------------------------
--------------------------- СПРАВКА 2 -----------------------------------------------------
-------------------------------------------------------------------------------------------
-- 151
select @link_row = link_row from report_rows where link_table = @link_table and orders = 18
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FORM = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FORM = 1))
-- 152
select @link_row = link_row from report_rows where link_table = @link_table and orders = 19
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FORM = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FORM = 2))
-- 153
select @link_row = link_row from report_rows where link_table = @link_table and orders = 20
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FORM = 3)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FORM = 3))
-- 154
select @link_row = link_row from report_rows where link_table = @link_table and orders = 21
-- 155
select @link_row = link_row from report_rows where link_table = @link_table and orders = 22
-------------------------------------------------------------------------------------------
--------------------------- КРОМЕ ТОГО ----------------------------------------------------
-------------------------------------------------------------------------------------------
-- 161
select @link_row = link_row from report_rows where link_table = @link_table and orders = 23
-- 162
select @link_row = link_row from report_rows where link_table = @link_table and orders = 24
-- 163
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL_LINK FROM EMPL_INCQUAL EI WHERE 2008 - YEAR(DATE_END) < 3
INSERT #TEMP
SELECT DISTINCT EMPL_LINK FROM EMPL_PROFP EP WHERE 2008 - YEAR(DATE_END) < 3

select @link_row = link_row from report_rows where link_table = @link_table and orders = 25
insert into report_summa
select @varKSsFLink,@link_col,@link_row, (SELECT COUNT(*) FROM (SELECT * FROM #EMPLS_INFO E LEFT JOIN #TEMP T ON E.LINK = T.EMPL) T WHERE ISNULL(T.EMPL,0) = 0)
-- 164
DELETE FROM #TEMP
INSERT #TEMP
SELECT DISTINCT EMPL FROM #EMPL_INCQUAL EI WHERE EXISTS(SELECT * FROM ITEM_DIS_FACE WHERE ACTIVE = 1 AND EMPL_LINK = EI.EMPL)
INSERT #TEMP
SELECT DISTINCT EMPL FROM #EMPL_PROFP EP WHERE EXISTS(SELECT * FROM ITEM_DIS_FACE WHERE ACTIVE = 1 AND EMPL_LINK = EP.EMPL)

select @link_row = link_row from report_rows where link_table = @link_table and orders = 26
insert into report_summa
select @varKSsFLink,@link_col,@link_row, (SELECT COUNT(*) FROM (SELECT DISTINCT EMPL FROM #TEMP) T)

-------------------------------------------------------------------------------------------
DROP TABLE #TEMP
--*******************************--
--********** РАЗДЕЛ 2 ***********--
--*******************************--
-- выбор таблицы
select @link_table = link_table from report_tables where link_form = @link_form and orders = 3
-- заполнение данных
-- **************************************************************
-- ***********************   3 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 3
-- 201
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 4 AND EI.DIR = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 4 AND EP.DIR = 1))
-- 203
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EI.DIR = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EP.DIR = 1))
-- 204
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EI.DIR = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EP.DIR = 1))
-- 205
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EI.DIR = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EP.DIR = 1))
-- 206
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EI.DIR = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EP.DIR = 1))
-- 207
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EI.DIR = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EP.DIR = 1))
-- **************************************************************
-- ***********************   4 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 4
-- 201
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 4 AND EI.DIR = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 4 AND EP.DIR = 2))
-- 203
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EI.DIR = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EP.DIR = 2))
-- 204
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EI.DIR = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EP.DIR = 2))
-- 205
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EI.DIR = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EP.DIR = 2))
-- 206
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EI.DIR = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EP.DIR = 2))
-- 207
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EI.DIR = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EP.DIR = 2))
-- **************************************************************
-- ***********************   5 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 5
-- 201
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 4 AND EI.DIR = 3)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 4 AND EP.DIR = 3))
-- 203
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EI.DIR = 3)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EP.DIR = 3))
-- 204
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EI.DIR = 3)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EP.DIR = 3))
-- 205
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EI.DIR = 3)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EP.DIR = 3))
-- 206
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EI.DIR = 3)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EP.DIR = 3))
-- 207
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EI.DIR = 3)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EP.DIR = 3))
-- **************************************************************
-- ***********************   6 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 6
-- 201
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 4 AND EI.DIR = 4)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 4 AND EP.DIR = 4))
-- 203
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EI.DIR = 4)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EP.DIR = 4))
-- 204
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EI.DIR = 4)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EP.DIR = 4))
-- 205
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EI.DIR = 4)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EP.DIR = 4))
-- 206
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EI.DIR = 4)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EP.DIR = 4))
-- 207
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EI.DIR = 4)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EP.DIR = 4))
-- **************************************************************
-- ***********************   7 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 7
-- 201
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 4 AND EI.DIR = 5)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 4 AND EP.DIR = 5))
-- 203
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EI.DIR = 5)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EP.DIR = 5))
-- 204
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EI.DIR = 5)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EP.DIR = 5))
-- 205
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EI.DIR = 5)
				  + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EP.DIR = 5))
-- 206
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EI.DIR = 5)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EP.DIR = 5))
-- 207
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EI.DIR = 5)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EP.DIR = 5))
-- **************************************************************
-- ***********************   8 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 8
-- 201
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 4 AND EI.DIR = 6)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 4 AND EP.DIR = 6))
-- 203
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EI.DIR = 6)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EP.DIR = 6))
-- 204
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EI.DIR = 6)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EP.DIR = 6))
-- 205
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EI.DIR = 6)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EP.DIR = 6))
-- 206
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EI.DIR = 6)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EP.DIR = 6))
-- 207
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EI.DIR = 6)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EP.DIR = 6))
-- **************************************************************
-- ***********************   9 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 9
-- 201
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 4 AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 4 AND EP.GOS = 1))
-- 203
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EP.GOS = 1))
-- 204
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EP.GOS = 1))
-- 205
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EP.GOS = 1))
-- 206
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EP.GOS = 1))
-- 207
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EI.GOS = 1)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EP.GOS = 1))
-- **************************************************************
-- ***********************  10 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 10
-- 201
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 4 AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 4 AND EP.GOS = 2))
-- 203
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 1 AND EP.GOS = 2))
-- 204
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 2 AND EP.GOS = 2))
-- 205
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 3 AND EP.GOS = 2))
-- 206
select @link_row = link_row from report_rows where link_table = @link_table and orders = 6
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 4 AND EP.GOS = 2))
-- 207
select @link_row = link_row from report_rows where link_table = @link_table and orders = 7
insert into report_summa
select @varKSsFLink,@link_col,@link_row,((select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EI.GOS = 2)
				       + (select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where E.GOSSL = 3 AND E.GR_GOS_CODE = 5 AND EP.GOS = 2))
--*******************************--
--********** РАЗДЕЛ 4 ***********--
--*******************************--
-- выбор таблицы
select @link_table = link_table from report_tables where link_form = @link_form and orders = 4
-- заполнение данных
-- **************************************************************
-- ***********************   4 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 4
--301
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FIN = 1)
--302
select @link_row = link_row from report_rows where link_table = @link_table and orders = 2
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FIN = 3)
--303
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FIN IN (5, 6))
--304
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FIN IN (7, 8, 9))
--305
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_PROFP EP ON E.LINK = EP.EMPL where EP.FIN = 7)

-- **************************************************************
-- ***********************   5 КОЛОНКА **************************
-- **************************************************************
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 5
--301
select @link_row = link_row from report_rows where link_table = @link_table and orders = 1
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FIN = 1)
--302
select @link_row = link_row from report_rows where link_table = @link_table and orders = 2
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FIN = 3)
--303
select @link_row = link_row from report_rows where link_table = @link_table and orders = 3
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FIN IN (5, 6))
--305
select @link_row = link_row from report_rows where link_table = @link_table and orders = 4
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FIN IN (7, 8, 9))
--306
select @link_row = link_row from report_rows where link_table = @link_table and orders = 5
insert into report_summa
select @varKSsFLink,@link_col,@link_row,(select COUNT(*) from #EMPLS_INFO E LEFT JOIN #EMPL_INCQUAL EI ON E.LINK = EI.EMPL where EI.FIN = 7)



DROP TABLE #EMPLS_INFO
DROP TABLE #EMPL_INCQUAL
DROP TABLE #EMPL_PROFP
select '' as Val


GO


GRANT EXECUTE ON dbo.[RJ_AUTOFILL_2MS_2016] TO PUBLIC

GO


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

GO



/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE [dbo].SD_O_OTHER_TABLE_SAVE
	@LINK			int,
	@ORDERS		numeric(5,0),
	@Summa		numeric(15,2)=0.0,
	@SummaBase 	numeric(15,2)=0.0,
	@PERCENT		numeric(6,2)=0.0,
	@REF_DED		int,
	@LinkVKR 	int,
	@LinkEKR 	int,
	@LinkVKR2 	int = NULL
AS
DECLARE @varKSERROR	tinyint, @varKStrancount	int

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

IF @LinkVKR2 IS NULL
	SET @LinkVKR2 = @LinkVKR

IF @REF_DED IS NULL OR @REF_DED = 0 OR @LinkVKR  IS NULL OR @LinkVKR = 0
BEGIN
	ROLLBACK
	RETURN 5
END

INSERT INTO dbo.SDOC_DOT_TABLE (LINK_UP,ORDERS,LINK_PAY,SUMMA_BASE,PERC,SUMMA,LINK_VKR,LINK_EKR,LINK_VKR2)
VALUES (@LINK,@ORDERS,@REF_DED,@SummaBase,@PERCENT,@Summa,@LinkVKR,@LinkEKR,@LinkVKR2)

WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0



GO


GRANT EXECUTE ON dbo.[SD_O_OTHER_TABLE_SAVE] TO PUBLIC

GO

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

GO




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


CREATE   PROCEDURE dbo.BK_REPORT_TRAVEL_OUT_FUEL
	@varKSdDate1	DATETIME,			 
	@varKSdDate2	DATETIME,			 
	@varKScVal1 CHAR(1), @varKSnOtborLink1 INT,
	@cKBK_Val CHAR(1), @intKBK_Otbor	INT

AS
BEGIN
	DECLARE @varKSCARS INT,
		@varKSDEP_LINK	INT,
		@varKSDIC_EMP	INT,
		@varKSORGNAME	VARCHAR(254),

		@intXO_MOVE	INT

	SELECT  @varKSDEP_LINK = LINK,
		@varKSORGNAME = [NAME]
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = COALESCE (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())		

	DECLARE @CARS  TABLE (LINK_AUTO INT, AUTO_CODE VARCHAR(20), AUTO_NAME VARCHAR(254) )
	IF LEN(@varKScVal1)>0
		INSERT INTO @CARS
		SELECT RECORD, CODE, [NAME] FROM dbo.OBJECT_VAR_INVENTORY, dbo.BK_DICTION_AUTO
			WHERE LINK_UP=@varKSnOtborLink1 AND LINK=RECORD
	ELSE BEGIN
		INSERT INTO @CARS
		SELECT LINK, CODE, [NAME] FROM dbo.BK_DICTION_AUTO
		INSERT INTO @CARS (LINK_AUTO, AUTO_CODE, AUTO_NAME) VALUES (0, '', 'Не указан')
	END

	--- ОТБОР ПО КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cKBK_Val) > 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 = @intKBK_Otbor
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	DECLARE @varKSDOC_INV TABLE		
		(LINK_DOC INT,
		INV	INT
		)

	INSERT INTO @varKSDOC_INV
	SELECT  LINK_WAYBILL, INV
	FROM dbo.WAYBILL_REFUEL
	WHERE UPPER (TYPE) = 'ТОПЛИВО'
	GROUP BY LINK_WAYBILL, INV 

	SELECT @intXO_MOVE = XO.LINK
	FROM dbo.XOZ_OPER XO 
	WHERE
		EXISTS (SELECT 1 FROM dbo.XOZ_OPER_GROUP XOG 
			WHERE XOG.CODE = '17' AND XO.GROUP_LINK = XOG.LINK)
		AND XO.CODE = '07'

	SET @intXO_MOVE = ISNULL (@intXO_MOVE, 0)

	DECLARE @TMP_RES  TABLE (LINK_DOC INT, INV INT,
		QTY NUMERIC (19,4), SUMMA NUMERIC (19,2))

	INSERT INTO @TMP_RES
	SELECT WR.LINK_DOC,
		WR.INV,
		SUM (QTY),
		SUM (SUMMA)
	FROM @varKSDOC_INV WR
	INNER JOIN dbo.BK_GetTableOborotByDate1 (@varKSdDate1, @varKSdDate2, 1, DEFAULT, @varKSDEP_LINK) G_Ob
		ON (G_Ob.LINK_DOC = WR.LINK_DOC
			AND G_Ob.NOMEN = WR.INV
			AND G_Ob.XOZ_OPER <> @intXO_MOVE)
	INNER JOIN @TAB_KBK KBK ON (KBK.LINK_KBK = G_Ob.KBK)
	GROUP BY WR.LINK_DOC,
			WR.INV
	
--	CREATE TABLE #RESULT (LINK_DOC INT, DOC_NUM NUMERIC (8),
	DECLARE @RESULT TABLE (LINK_DOC INT, DOC_NUM VARCHAR (30),
		DOC_DATE VARCHAR (10),
		CAR_CODE VARCHAR (20), CAR_NAME VARCHAR (254),
		EMP_CODE VARCHAR (20), EMP_NAME VARCHAR (254),
		KM_BEFORE NUMERIC (9,2), KM_AFTER NUMERIC (9,2),
		KM_TOTAL NUMERIC (9,2), 
		QTY NUMERIC (19,4), SUMMA NUMERIC (19,2),
		ORGNAME VARCHAR (254),
		dDOC_DATE DATETIME)

	INSERT INTO @RESULT
	SELECT T1.LINK_DOC,
		G.NUMBER,
		CONVERT (VARCHAR (10), G.[DATE], 104),
		CARS_T.AUTO_CODE,
		CARS_T.AUTO_NAME,
		EMP.TAB,
		EMP.[NAME_EMPL],

		CONVERT (NUMERIC (9,2), DISPLAY_B),
		CONVERT (NUMERIC (9,2), DISPLAY_A),
		CONVERT (NUMERIC (9,2), ABS (DISPLAY_B - DISPLAY_A)),

		T1.QTY,
		T1.SUMMA,
		@varKSORGNAME,
		G.[DATE]
	FROM @TMP_RES T1
	INNER JOIN dbo.G_PROV G ON (G.LINK = T1.LINK_DOC)
	INNER JOIN dbo.WAYBILL_REESTR WR ON (WR.LINK_WAYBILL = T1.LINK_DOC)
	INNER JOIN @CARS CARS_T ON (CARS_T.LINK_AUTO = WR.CAR)
	INNER JOIN dbo.KU_EMPL_PLACING EMP ON (EMP.LINK = WR.DRIVER)
	
	SELECT * FROM @RESULT
		ORDER BY CAR_CODE, dDOC_DATE, 
			REPLACE (SPACE (20 - LEN (DOC_NUM)) + RTRIM (DOC_NUM), SPACE (1), '0')
	
END



GO


GRANT EXECUTE ON dbo.[BK_REPORT_TRAVEL_OUT_FUEL] 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.[SD_NUO_DGH_TABLE_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_NUO_DGH_TABLE_SAVE]

GO

CREATE   PROCEDURE [dbo].SD_NUO_DGH_TABLE_SAVE

	@LINK		int,
	@cCodeObject 	varchar(100),
	@ORDERS  	int = null,
	@PERS_LINK	int = null,
	@LinkPay	int = null,
	@Summa	numeric(15,2) = 0.0,
	@LinkDog	int = null,
	@BASE_YEAR  numeric(15,2) = 0.0,
	@SummaBase	numeric(15,2) = 0.0,
	@V_SUM_Y	numeric(15,2) = 0.0,
	@V_SUM_M	numeric(15,2) = 0.0,
	@PERCENT	numeric(15,2) = 0.0,
	@SUMMA_YEAR	numeric(15,2) = 0.0,
	@SUMMA_OLD	numeric(15,2) = 0.0,
	@LinkVKR	int,
	@LinkEKR	int,
	@LinkVKR2	int = NULL
AS
DECLARE @ERROR	tinyint, @trancount	int, @soObject int, @SQLError int


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

IF EXISTS (SELECT * FROM dbo.PAYS WHERE LINK = @LinkPay AND [OBJECT] = 3) AND @LinkVKR2 IS NULL
	SET @LinkVKR2 = @LinkVKR
	

IF @LinkDog = 0
	SET @LinkDog = NULL

SET @soObject = (SELECT TOP 1 P.[OBJECT] FROM dbo.PAYS P WHERE LINK = @LinkPay)

IF @LINK IS NULL OR @LINK =0 OR  @ORDERS IS NULL  OR  @PERS_LINK IS NULL or @LinkPay is null  or @LinkVKR is null
BEGIN
	ROLLBACK
	RETURN 5
END

INSERT INTO SDOC_DGH_TABLE WITH (ROWLOCK) (LINK_UP, OBJECT, ORDERS, PERS_LINK, LINK_PAY, SUMMA_BASE, SUMMA, LINK_DOG,LINK_VKR,LINK_EKR, SUMMA_YEAR, SUMMA_OLD,BASE_YEAR,[PERCENT], V_SUM_Y, V_SUM_M, LINK_VKR2) 
VALUES (@LINK, @soObject, @ORDERS, @PERS_LINK, @LinkPay, @SummaBase, @Summa, @LinkDog, @LinkVKR, @LinkEKR, @SUMMA_YEAR, @SUMMA_OLD, @BASE_YEAR, @PERCENT, @V_SUM_Y, @V_SUM_M, @LinkVKR2)

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

WHILE @@TRANCOUNT > @trancount
	COMMIT TRAN
RETURN 0




GO


GRANT EXECUTE ON dbo.[SD_NUO_DGH_TABLE_SAVE] 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.[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.[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 IN('DICTIONARY_POST','DICTIONARY_SUBDIVISION','KU_PERSON','KU_EMPL'))
	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.[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.[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.[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, '2884.16'
		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 1 ребенком = 2884.16', '', 'SALARY'


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

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


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

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

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

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


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

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

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

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Максимальный размер пособия по беременности и родам = 59833.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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

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

*******************************************************************************/
CREATE PROCEDURE dbo.[I_REPORT_CREATE_PROC]
	@iLINK_TABLE INT,
	@cTmpName Varchar(50)='', --требуется для подсчета подитогов 428 формы
	@iType  int  =0 --для архивных таблиц. 0 - хранимка вызова. 1 - обычная хранимка выборки, 2 - выборка из _ARH,3 - для временных таблиц
AS
   SET NOCOUNT ON
	declare @varKSRunStr	varchar(8000),
        @varKSRunStr05 varchar(8000),
		@varKSRunStr1	varchar(8000),
		@varKScStr2	varchar(8000),
		@varKScStr3	varchar(8000),
		@varKScStr3_1	varchar(8000),
        @varKSRunStrF	varchar(8000),
        @varKSRunStr05F varchar(8000),
		@varKSRunStr1F	varchar(8000),
		@varKScStr2F	varchar(8000),
		@varKScStr3F_1	varchar(8000),
		@varKScStr3F	varchar(8000),
		@varKSViewName	varchar(50),
		@varKSLink_Col	int,
		@varKSOrders		tinyint,
		@varKSiColType	tinyint,
		@varKSiLen		int,
		@varKSiIsEdit	tinyint,
		@varKSname		varchar(70),
		@varKSiVal_Type	tinyint,
		@varKSLink_Code_Col	int,
		@col_ord_for_sort int,@order_rule varchar(4000),@count_rule int,@i int,@order_rule_new varchar(8000),@order_rule_curr varchar(8000)

	DECLARE SEL_CURSOR  CURSOR STATIC LOCAL
	FOR SELECT DISTINCT LINK_Col, ORDERS, Name, Col_Type, Val_Len, IsEdited
	FROM report_coloumns WHERE LINK_Table=@iLINK_TABLE
	order by orders
	declare @cSuffix_proc varchar(200),@csuffix_table varchar(200)

set @cSuffix_table=''
set @cSuffix_PROC=''
IF @iType=1
	begin
		set @cSuffix_table=''
		set @cSuffix_proc='_OPER'
	end
IF @iType=2
	begin
		set @cSuffix_table='_ARH'
		set @cSuffix_proc='_ARH'
	end
IF @iType=3
	begin
		set @cSuffix_table=''
		set @cSuffix_proc=''
	end



SET @varKSRunStr1 = ''
set @varKSRunStr05=''
SET @varKScStr2 = ''	
SET @varKScStr3 = '' 
SET @varKScStr3_1 = '' 
SET @varKSRunStr1F = ''
set @varKSRunStr05F=''
SET @varKScStr2F = ''	
SET @varKScStr3F = '' 

declare @is_dinamic int 
IF exists (select link_Table from report_tables where link_Table = @iLINK_TABLE)
BEGIN
	select @is_dinamic=isnull(is_dinamic,0),@varKSiVal_Type = val_type, @varKSLink_Code_Col = Link_Code_Col,@order_rule=rtrim(isnull(order_rule,'')) from report_tables where link_table = @iLINK_TABLE
	set @order_rule_new=''
	--превратим @order_rule в условие
	IF @order_rule<>''
		begin
			set @order_rule_new=' case '
			set @count_rule=dbo.rn_getwordcount(@order_rule,char(13))
			set @i=1
			while @i<=@count_rule
				begin
					set @count_rule=dbo.rn_getwordcount(@order_rule,char(13))
					set @order_rule_curr=rtrim(dbo.rn_getwordnum(@order_rule,@i,char(13)))
					IF  @order_rule_curr<>''
						set @order_rule_new=@order_rule_new +' when '+ replace(UPPER(dbo.rn_getwordnum(@order_rule_curr,2,'#')),'CODE','RR.CODE_ROW')+' then '+dbo.rn_getwordnum(@order_rule_curr,1,'#')
					set @i=@i+1
				end
			set @order_rule_new=@order_rule_new+' else 0 end ' 
		end
--print @order_rule_new
	set @varKSViewName = 'dbo.RI_PROC_T'+ltrim(rtrim(@cTmpName))+ ltrim(rtrim(@iLINK_TABLE))+@cSuffix_proc
	set @varKSRunStr = ' PROCEDURE ' + @varKSViewName + '
@varKSLSF	int,
@varKSpTYPE	int=1,
@varKSPNom	int=1,
@varKSpDATE	datetime=''01/01/2003'',
@varKScCodeRow	varchar(100)='''',
@iLINK_SAVED_FORM INT = NULL,
@bDeleteEmptyRows BIT = NULL,
@tmp_table varchar(100) = '''',
@del_fcol int=0,
@all_str int =0
AS
--  Генератор I_REPORT_CREATE_PROC
--'+LTRIM(convert(char, getdate()))+'
declare @varKScode_Col	int
declare @cexec varchar(5000)
declare	@varKSLTable	int,
			@varKSLForm	int,
			@varKSLRow	int,
			@varKScCode	char(7)

select @varKScode_Col = Link_Code_Col from Report_Tables where link_table = '+ convert(varchar,@iLINK_TABLE) +'
IF @del_fcol=0 
 begin

IF @varKSLSF > 0 BEGIN
SELECT checked=0,UPD=0,del=0,link_saved_form=@varKSLSF,'
IF @varKSiVal_Type = 0 
	set @varKSRunStr = @varKSRunStr + ' rr.link_row, rr.orders, rr.Calc_orders, rr.Print_Null,
isnull((select convert(char(100),formula) from report_formula RF where RF.link_row = RR.link_row and link_col = @varKScode_Col ),'''') as code'
ELSE 
	set @varKSRunStr = @varKSRunStr + ' 0 as link_row, '+case when @order_rule<>'' then @order_rule_new else '0' end+' as orders, 0 as Calc_orders, 0 as Print_Null,
RR.Code_Row as code'

create table #Exec (ExecStr varchar(8000), orders int)
insert #Exec (ExecStr, orders)
values(@varKSRunStr, 1)

SET @varKScStr2 = ''
OPEN SEL_CURSOR
FETCH NEXT FROM SEL_CURSOR INTO @varKSLink_Col, @varKSOrders, @varKSname, @varKSiColType, @varKSiLen, @varKSiIsEdit

WHILE @@FETCH_STATUS = 0
BEGIN
	IF @varKSiLen<=0 and @varKSiColType=1
		set @varKSiLen=254
	set @varKScStr3 = ''
	IF @varKSiVal_Type = 0
	BEGIN /* Стандартные таблицы */
		IF @varKSiColType = 0
		BEGIN
			set @varKSRunStr = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) + '= coalesce((select convert(numeric(20,' + convert(char(2),@varKSiLen) + '),summa) from '+ltrim(rtrim(@cTmpName))+'report_summa'+@cSuffix_table+'  where link_saved_form = SF.link_saved_form and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' and Link_Row = RR.link_Row),0),
fcol' + ltrim(convert(varchar(7),@varKSOrders)) + '= (select left(RTRIM(formula),2500) from report_formula where link_Col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and Link_Row = RR.link_Row)'
		END
		ELSE
		BEGIN
			IF @varKSiIsEdit = 0
				set @varKSRunStr =',
isnull((select left(formula,'+ltrim(str(case when @varKSiColType=0 or @varKSiLen<250 then 254 else @varKSiLen end))+') from report_Formula RF where link_col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and RF.link_row = RR.link_row ),'''') as col' + ltrim(convert(varchar(7),@varKSOrders))
			ELSE
				set @varKSRunStr = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) + '= isnull((select convert(varchar(' + convert(char(4),@varKSiLen) + '),str_val) from report_string'+@cSuffix_table+'  where link_saved_form = SF.link_saved_form and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' and Link_Row = RR.link_Row),''''),
fcol' + ltrim(convert(varchar(7),@varKSOrders)) + '= (select left(RTRIM(formula),'+ltrim(str(@varKSiLen))+') from report_formula where link_Col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and Link_Row = RR.link_Row)'
		END
		IF @varKSiIsEdit = 0
			set @varKScStr2 =  ',
isnull((select left(formula,'+ltrim(str(case when @varKSiColType=0 or @varKSiLen<250 then 254 else @varKSiLen end))+') from report_formula RF where link_col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and RF.link_row = RR.link_row ),'''') as col' + ltrim(convert(varchar(7),@varKSOrders))
		ELSE 
		BEGIN
			IF @varKSiColType = 0
				set @varKScStr2 = ',
convert (numeric(20,' + convert(char(2),@varKSiLen) + '),0) as col'+ ltrim(convert(varchar(7),@varKSOrders))
			ELSE
				set @varKScStr2 =',
isnull(convert (VarChar(' + convert(char(4),@varKSiLen) + '),''''),'''') as col'+ ltrim(convert(varchar(7),@varKSOrders))
   			SET @varKScStr2 = @varKScStr2+',
fcol' + ltrim(convert(varchar(7),@varKSOrders)) + '= (select left(RTRIM(formula),2500) from report_formula where link_Col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and Link_Row = RR.link_Row)'
		END

		IF @varKSiColType = 0
			set @varKScStr3 = ',
isnull(convert(numeric(20,' + convert(char(2),@varKSiLen) + '),coalesce((select summa  from report_summa_all  where link_row=@varKSLRow and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col)) +' and link_saved_Form = RSF.link_saved_Form),0)),0) as col' + ltrim(rtrim(convert(varchar(5),@varKSOrders)))
	END
	ELSE /* Для динамических таблиц */
	BEGIN
		IF @varKSiColType = 0
		BEGIN
			SET @varKSRunStr = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) 
	+ '= convert(numeric(20,' + convert(char(2),@varKSiLen) 
	+ '),SUM(case when link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' then float_val else 0 end)),
fcol' + ltrim(convert(varchar(7),@varKSOrders)) + '= CAST('''' AS VARCHAR) '
			SET @varKScStr2 = ',
convert (numeric(20,' + convert(char(2),@varKSiLen) + '),0) as col'+ ltrim(convert(varchar(7),@varKSOrders))
	/* Переписать для расшифровки динамически сведеных таблиц */
			SET @varKScStr3 = ',
convert(numeric(20,' + convert(char(2),@varKSiLen) + '),coalesce((select float_val  from '+ltrim(rtrim(@cTmpName))+'REPORT_DINAMICS_ALL  where code_row=@varKScCodeRow and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col)) +' and Link_SF = RSF.link_saved_Form),0)) as col' + ltrim(rtrim(convert(varchar(5),@varKSOrders)))
		END
		ELSE
		BEGIN
			IF @varKSiLen = 0
				SET @varKSiLen = 254
			IF @varKSLink_Code_Col = @varKSLink_Col
			BEGIN /* ключевой столбец */
				SET @varKSRunStr = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) + '= RR.Code_Row '
				SET @varKScStr2 = ',
convert (VarChar(' + convert(char(4),@varKSiLen) + '),'''') as col'+ ltrim(convert(varchar(7),@varKSOrders))
			END
			ELSE
			BEGIN /* обычный текстовый столбец */
				SET @varKSRunStr = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) 
	+ '= isnull(convert(varchar(' + convert(char(4),@varKSiLen) 
	+ '),MAX(case when link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' then str_val else '''' end)),''''),
fcol' + ltrim(convert(varchar(7),@varKSOrders)) + '= CAST('''' AS VARCHAR) '
				SET @varKScStr2 = ',
isnull(convert (VarChar(' + convert(char(4),@varKSiLen) + '),''''),'''') as col'+ ltrim(convert(varchar(7),@varKSOrders))
			END
		END

		SET @varKScStr2 = @varKScStr2 + ',
fcol' + ltrim(convert(varchar(7),@varKSOrders)) + '= CAST('''' AS VARCHAR) '
	END

	insert #Exec (ExecStr, orders)
	values(@varKSRunStr, 10 + @varKSOrders)		

	insert #Exec (ExecStr, orders)
	values(@varKScStr2, 200 + @varKSOrders)		

	insert #Exec (ExecStr, orders)
	values(@varKScStr3, 400 + @varKSOrders)		
	FETCH NEXT FROM SEL_CURSOR INTO @varKSLink_Col, @varKSOrders, @varKSname, @varKSiColType, @varKSiLen, @varKSiIsEdit
END

CLOSE SEL_CURSOR

IF @varKSiVal_Type = 0 
BEGIN
	set @col_ord_for_sort = 0
	select @col_ord_for_sort = isnull(orders,0) from dbo.report_coloumns where link_table = @iLINK_TABLE and ([property] & 8) > 0
	SET @varKSRunStr05 =',
itog = 0
INTO #tabTable
FROM report_rows RR, report_saved_forms SF
WHERE RR.link_table =' + convert(varchar,@iLINK_TABLE) + '
AND SF.link_saved_form = @varKSLSF'+case when @is_dinamic=1 then 
' and (exists(select link_row from report_string'+@cSuffix_table+' RS where RS.link_saved_form=@varKSLSF and RS.link_row=RR.link_row)
or exists(select link_row from '+ltrim(rtrim(@cTmpName))+'report_summa'+@cSuffix_table+' RS where RS.link_saved_form=@varKSLSF and RS.link_row=RR.link_row))'
else '' end+
'
ORDER by orders
IF @bDeleteEmptyRows = 1 EXEC dbo.[RA_DELETE_EMPTY_ROWS] ' + CAST(@varKSiVal_Type AS VARCHAR)+ '


IF @tmp_table<>''''
 begin
    set @cExec=''SELECT * INTO ''+@tmp_table+'' FROM #tabTable order by orders ''
    execute(@cExec)
 end
 else   
    SELECT * FROM #tabTable order by '+ case @col_ord_for_sort when 0 then 'orders' else 'col'+cast(@col_ord_for_sort as varchar) end+' 
 
    DROP TABLE #tabTable

END
ELSE 
    IF @varKSLSF = 0 
	SELECT  0 as checked,  0 as UPD, 0 as del, @varKSLSF as link_saved_form, rr.link_row, rr.orders, rr.Calc_orders, rr.Print_Null,
(select convert(char(100),formula) from report_formula RF where RF.link_row = RR.link_row and link_col = @varKScode_Col ) as code'
	
SET @varKScStr2 = ',
itog = 0
	FROM report_rows RR 
	WHERE RR.link_table =' + convert(varchar,@iLINK_TABLE)+case when @is_dinamic=1 then ' and 1 = case when @all_str=0 then 0 else 1 end' else '' end+'
	ORDER by orders'
END
ELSE 
BEGIN
	set @col_ord_for_sort = 0
	select @col_ord_for_sort = isnull(orders,0) from dbo.report_coloumns where link_table = @iLINK_TABLE and ([property] & 8) > 0
	SET @varKSRunStr05 = '
   INTO #tabTable
	FROM (select RD.* from (select distinct Code_Row, Link_SF from '+ltrim(rtrim(@cTmpName))+'report_dinamics'+@cSuffix_table+' RD  inner join report_coloumns RC on RD.Link_SF = @varKSLSF and RD.Link_Col = RC.Link_Col and RC.Link_Table = ' + convert(varchar,@iLINK_TABLE) + ') RR
		left join '+ltrim(rtrim(@cTmpName))+'report_dinamics'+@cSuffix_table+' RD  on RD.Link_SF = RR.Link_SF and RR.Code_Row = RD.Code_Row 
        where RD.Link_SF=@varKSLSF) RR
	group by RR.Code_Row
	order by RR.Code_Row

  IF @bDeleteEmptyRows = 1
   BEGIN
      EXEC dbo.[RA_DELETE_EMPTY_ROWS] ' + CAST(@varKSiVal_Type AS VARCHAR)+ '
   END

    IF @tmp_table<>''''
     begin
        set @cExec=''SELECT * INTO ''+@tmp_table+'' FROM #tabTable order by orders ''
        execute(@cExec)
     end
     else   
        SELECT * FROM #tabTable order by '+ case @col_ord_for_sort when 0 then 'orders' else 'col'+cast(@col_ord_for_sort as varchar) end+' 

   DROP TABLE #tabTable
END
ELSE
    IF @varKSLSF = 0 
	SELECT  0 as checked,  0 as UPD, 0 as del, @varKSLSF as link_saved_form, 0 as link_row, 0 as orders, 0 as Calc_orders, 0 as Print_Null,

convert(varchar(100),'''') as code'

	SET @varKScStr2 = '
	FROM I_REPORT_DINAMIC_ROWS RR
	WHERE RR.link_SF = @varKSLSF
		and RR.link_table = ' + convert(varchar,@iLINK_TABLE) + '
'
END

insert #Exec (ExecStr, orders)
values(@varKSRunStr05, 100 )		

insert #Exec (ExecStr, orders)
values(@varKScStr2, 300 )		

IF @varKSiVal_Type = 0 
	set @varKScStr3 = '
	ELSE 
	BEGIN

		set @varKSLRow = - @varKSLSF
		select @varKSLTable = link_table from report_rows where link_row = @varKSLRow
	
		select @varKSLForm = link_Form from report_tables where link_table = @varKSLTable
		select @varKScCode = code from report_forms where link_form = @varKSLForm
		select 0 ord,left((select case when left(name,1) like ''[0-9]'' then '''' else  rtrim(code)+'' '' end +rtrim([name]) from dbo.DICTIONARY_DEPARTMENT where link=link_organization)+'' - ''+isnull((select [name] from dbo.KL_BUDG_TYPE A where A.link=link_type_svod),''''),254) as Org' 
ELSE  /* расшифровка для динамических таблиц */
	set @varKScStr3 = '
	ELSE 
	BEGIN
	select @varKScCode = code from report_forms where link_form = (select max(link_Form) from report_tables where link_table = ' +ltrim(rtrim(convert(varchar(10), @iLINK_TABLE))) + ')
		select 0 ord, left((select case when left(name,1) like ''[0-9]'' then '''' else  rtrim(code)+'' '' end +rtrim([name]) from dbo.DICTIONARY_DEPARTMENT where link=link_organization)+'' - ''+isnull((select [name] from dbo.KL_BUDG_TYPE A where A.link=link_type_svod),''''),254) as Org' 

insert #Exec (ExecStr, orders)
values(@varKScStr3, 310 )		

set @varKScStr3_1 =  '
,Link_Tree, Link_Tree_Self, childrens, FilterField
        into   #tabTable6       
		from dbo.[RA_SELECT_SVOD_FORMS](@iLINK_SAVED_FORM) RSF

    IF @tmp_table<>''''
     begin
        set @cExec=''SELECT * INTO ''+@tmp_table+'' FROM #tabTable6  ''
        execute(@cExec)
     end
     else   
        SELECT B.* FROM 
        dbo.[RA_SELECT_SVOD_FORMS2](@iLINK_SAVED_FORM) A
        INNER JOIN #tabTable6 B  ON A.Link_Tree = B.Link_Tree
        order by A.[level]

        DROP TABLE #tabTable6

END
END
ELSE
BEGIN
--удаление fcol
IF @varKSLSF > 0 BEGIN
SELECT checked=0,UPD=0,del=0,link_saved_form=@varKSLSF,'

insert #Exec (ExecStr, orders)
values(@varKScStr3_1, 600 )	

set @varKSRunStrF=''

select @varKSiVal_Type = val_type, @varKSLink_Code_Col = Link_Code_Col from report_tables where link_table = @iLINK_TABLE
IF @varKSiVal_Type = 0 
	set @varKSRunStrF = ' rr.link_row, rr.orders, rr.Calc_orders, rr.Print_Null,
isnull((select convert(char(100),formula) from report_formula RF where RF.link_row = RR.link_row and link_col = @varKScode_Col ),'''') as code'
ELSE 
	set @varKSRunStrF =  ' 0 as link_row, '+case when @order_rule<>'' then @order_rule_new else '0' end+' as orders, 0 as Calc_orders, 0 as Print_Null,
RR.Code_Row as code'

insert #Exec (ExecStr, orders)
values(@varKSRunStrF, 800 )

SET @varKScStr2F = ''

OPEN SEL_CURSOR
FETCH NEXT FROM SEL_CURSOR INTO @varKSLink_Col, @varKSOrders, @varKSname, @varKSiColType, @varKSiLen, @varKSiIsEdit
WHILE @@FETCH_STATUS = 0
BEGIN
	IF @varKSiLen<=0 and @varKSiColType=1
		set @varKSiLen=254
	set @varKScStr3F = ''
	IF @varKSiVal_Type = 0
	BEGIN /* Стандартные таблицы */
		IF @varKSiColType = 0
		BEGIN
			set @varKSRunStrF = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) + '= coalesce((select convert(numeric(20,' + convert(char(2),@varKSiLen) + '),summa) from '+ltrim(rtrim(@cTmpName))+'report_summa'+@cSuffix_table+' where link_saved_form = SF.link_saved_form and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' and Link_Row = RR.link_Row),0)'
		END
		ELSE
		BEGIN
			IF @varKSiIsEdit = 0
				set @varKSRunStrF = ',
isnull((select left(formula,'+ltrim(str(@varKSiLen))+') from report_Formula RF where link_col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and RF.link_row = RR.link_row ),'''') as col' + ltrim(convert(varchar(7),@varKSOrders))
			ELSE
				set @varKSRunStrF = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) + '= isnull((select convert(varchar(' + convert(char(4),@varKSiLen) + '),str_val) from report_string'+@cSuffix_table+' where link_saved_form = SF.link_saved_form and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' and Link_Row = RR.link_Row),'''')'
		END
		IF @varKSiIsEdit = 0
			set @varKScStr2F = ',
(select left(formula,'+ltrim(str(@varKSiLen))+') from report_formula RF where link_col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and RF.link_row = RR.link_row ) as col' + ltrim(convert(varchar(7),@varKSOrders))
		ELSE 
		BEGIN
			IF @varKSiColType = 0
				set @varKScStr2F = ',
convert (numeric(20,' + convert(char(2),@varKSiLen) + '),0) as col'+ ltrim(convert(varchar(7),@varKSOrders))
			ELSE
				set @varKScStr2F = ',
convert (VarChar(' + convert(char(4),@varKSiLen) + '),'''') as col'+ ltrim(convert(varchar(7),@varKSOrders))

		END

		IF @varKSiColType = 0
			set @varKScStr3F = ',
convert(numeric(20,' + convert(char(2),@varKSiLen) + '),coalesce((select summa  from '+ltrim(rtrim(@cTmpName))+'report_summa_all where link_row=@varKSLRow and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col)) +' and link_saved_Form = RSF.link_saved_Form),0)) as col' + ltrim(rtrim(convert(varchar(5),@varKSOrders)))
	END
	ELSE /* Для динамических таблиц */
	BEGIN
		IF @varKSiColType = 0
		BEGIN
			SET @varKSRunStrF = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) 
	+ '= convert(numeric(20,' + convert(char(2),@varKSiLen) 
	+ '),SUM(case when link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' then float_val else 0 end))'
			SET @varKScStr2F = ',
convert (numeric(20,' + convert(char(2),@varKSiLen) + '),0) as col'+ ltrim(convert(varchar(7),@varKSOrders))
	/* Переписать для расшифровки динамически сведеных таблиц */
			SET @varKScStr3F = ',
convert(numeric(20,' + convert(char(2),@varKSiLen) + '),coalesce((select float_val  from '+ltrim(rtrim(@cTmpName))+'REPORT_DINAMICS_ALL  where code_row=@varKScCodeRow and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col)) +' and Link_SF = RSF.link_saved_Form),0)) as col' + ltrim(rtrim(convert(varchar(5),@varKSOrders)))
		END
		ELSE
		BEGIN
			IF @varKSiLen = 0
				SET @varKSiLen = 254
			IF @varKSLink_Code_Col = @varKSLink_Col
			BEGIN /* ключевой столбец */
				SET @varKSRunStrF = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) + '= RR.Code_Row '
				SET @varKScStr2F = ',
convert (VarChar(' + convert(char(4),@varKSiLen) + '),'''') as col'+ ltrim(convert(varchar(7),@varKSOrders))
			END
			ELSE
			BEGIN /* обычный текстовый столбец */
				SET @varKSRunStrF = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) 
	+ '= (convert(varchar(' + convert(char(4),@varKSiLen) 
	+ '),MAX(case when link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' then str_val else '''' end)))'
				SET @varKScStr2F = ',
convert (VarChar(' + convert(char(4),@varKSiLen) + '),'''') as col'+ ltrim(convert(varchar(7),@varKSOrders))
			END
		END
	END

	insert #Exec (ExecStr, orders)
	values(@varKSRunStrF, 800 + @varKSOrders)		

	insert #Exec (ExecStr, orders)
	values(@varKScStr2F, 1000 + @varKSOrders)		

	insert #Exec (ExecStr, orders)
	values(@varKScStr3F, 1200 + @varKSOrders)		

	FETCH NEXT FROM SEL_CURSOR INTO @varKSLink_Col, @varKSOrders, @varKSname, @varKSiColType, @varKSiLen, @varKSiIsEdit
END

CLOSE SEL_CURSOR
DEALLOCATE SEL_CURSOR

IF @varKSiVal_Type = 0 
BEGIN
	set @col_ord_for_sort = 0
	select @col_ord_for_sort = isnull(orders,0) from dbo.report_coloumns where link_table = @iLINK_TABLE and ([property] & 8) > 0
	SET @varKSRunStr05F =',
itog = 0
INTO #tabTable1
FROM report_rows RR, report_saved_forms SF
WHERE RR.link_table =' + convert(varchar,@iLINK_TABLE) + '
AND SF.link_saved_form = @varKSLSF'+case when @is_dinamic=1 then 
' and (exists(select link_row from report_string'+@cSuffix_table+' RS where RS.link_saved_form=@varKSLSF and RS.link_row=RR.link_row)
or exists(select link_row from '+ltrim(rtrim(@cTmpName))+'report_summa'+@cSuffix_table+' RS where RS.link_saved_form=@varKSLSF and RS.link_row=RR.link_row))'
else '' end+'
ORDER by orders
IF @bDeleteEmptyRows = 1 EXEC dbo.[RA_DELETE_EMPTY_ROWS] ' + CAST(@varKSiVal_Type AS VARCHAR)+ ',''tabTable1''

IF @tmp_table<>''''
 begin
    set @cExec=''SELECT * INTO ''+@tmp_table+'' FROM #tabTable1 order by orders ''
    execute(@cExec)
 end
 else   
    SELECT * FROM #tabTable1 order by '+ case @col_ord_for_sort when 0 then 'orders' else 'col'+cast(@col_ord_for_sort as varchar) end+'
 
    DROP TABLE #tabTable1

END
ELSE 
    IF @varKSLSF = 0 
	SELECT  0 as checked,  0 as UPD, 0 as del, @varKSLSF as link_saved_form, rr.link_row, rr.orders, rr.Calc_orders, rr.Print_Null,
(select convert(char(100),formula) from report_formula RF where RF.link_row = RR.link_row and link_col = @varKScode_Col ) as code'
	
SET @varKScStr2F = ',
itog = 0
	FROM report_rows RR 
	WHERE RR.link_table =' + convert(varchar,@iLINK_TABLE)+case when @is_dinamic=1 then ' and 1 = case when @all_str=0 then 0 else 1 end' else '' end+'
	ORDER by orders'
END
ELSE 
BEGIN
	set @col_ord_for_sort = 0
	select @col_ord_for_sort = isnull(orders,0) from dbo.report_coloumns where link_table = @iLINK_TABLE and ([property] & 8) > 0
	SET @varKSRunStr05F = '
   INTO #tabTable1
	FROM (select RD.* from (select distinct Code_Row, Link_SF from '+ltrim(rtrim(@cTmpName))+'report_dinamics'+@cSuffix_table+' RD  inner join report_coloumns RC on RD.Link_SF = @varKSLSF and RD.Link_Col = RC.Link_Col and RC.Link_Table = ' + convert(varchar,@iLINK_TABLE) + ') RR
		left join '+ltrim(rtrim(@cTmpName))+'report_dinamics'+@cSuffix_table+' RD  on RD.Link_SF = RR.Link_SF and RR.Code_Row = RD.Code_Row 
        where RD.Link_SF=@varKSLSF) RR
	group by RR.Code_Row
	order by RR.Code_Row

  IF @bDeleteEmptyRows = 1
   BEGIN
      EXEC dbo.[RA_DELETE_EMPTY_ROWS] ' + CAST(@varKSiVal_Type AS VARCHAR)+ ',''tabTable1''
   END

    IF @tmp_table<>''''
     begin
        set @cExec=''SELECT * INTO ''+@tmp_table+'' FROM #tabTable1 order by orders, code ''
        execute(@cExec)
     end
     else   
        SELECT * FROM #tabTable1 order by '+ case @col_ord_for_sort when 0 then 'orders, code' else 'col'+cast(@col_ord_for_sort as varchar) end+'

   DROP TABLE #tabTable1
END
ELSE
    IF @varKSLSF = 0 
	SELECT  0 as checked,  0 as UPD, 0 as del, @varKSLSF as link_saved_form, 0 as link_row, 0 as orders, 0 as Calc_orders, 0 as Print_Null,

convert(varchar(100),'''') as code'

	SET @varKScStr2F = '
	FROM I_REPORT_DINAMIC_ROWS RR
	WHERE RR.link_SF = @varKSLSF
		and RR.link_table = ' + convert(varchar,@iLINK_TABLE) + '
'
END

insert #Exec (ExecStr, orders)
values(@varKSRunStr05F, 900)		

insert #Exec (ExecStr, orders)
values(@varKScStr2F, 1100 )		

IF @varKSiVal_Type = 0 
	set @varKScStr3F_1 = '
	ELSE 
	BEGIN
		set @varKSLRow = - @varKSLSF
		select @varKSLTable = link_table from report_rows where link_row = @varKSLRow
	
		select @varKSLForm = link_Form from report_tables where link_table = @varKSLTable
		select @varKScCode = code from report_forms where link_form = @varKSLForm
		select 0 ord,left((select case when left(name,1) like ''[0-9]'' then '''' else  rtrim(code)+'' '' end +rtrim([name]) from dbo.DICTIONARY_DEPARTMENT where link=link_organization)+'' - ''+isnull((select [name] from dbo.KL_BUDG_TYPE A where A.link=link_type_svod),''''),254) as Org' 
ELSE  /* расшифровка для динамических таблиц */
	set @varKScStr3F_1 = '
	ELSE 
	BEGIN
	select @varKScCode = code from report_forms where link_form = (select max(link_Form) from report_tables where link_table = ' +ltrim(rtrim(convert(varchar(10), @iLINK_TABLE))) + ')
		select 0 ord,left((select case when left(name,1) like ''[0-9]'' then '''' else  rtrim(code)+'' '' end +rtrim([name]) from dbo.DICTIONARY_DEPARTMENT where link=link_organization)+'' - ''+isnull((select [name] from dbo.KL_BUDG_TYPE A where A.link=link_type_svod),''''),254) as Org'

	set @varKScStr3F = '
	,Link_Tree, Link_Tree_Self, childrens, FilterField
        into   #tabTable5       
		from dbo.[RA_SELECT_SVOD_FORMS](@iLINK_SAVED_FORM) RSF

    IF @tmp_table<>''''
     begin
        set @cExec=''SELECT * INTO ''+@tmp_table+'' FROM #tabTable4  ''
        execute(@cExec)
     end
     else   
        SELECT * FROM #tabTable4 

        SELECT B.* FROM 
        dbo.[RA_SELECT_SVOD_FORMS2](@iLINK_SAVED_FORM) A
        INNER JOIN #tabTable4 B  ON A.Link_Tree = B.Link_Tree
        order by A.[level]

        DROP TABLE #tabTable4


END


END

'
 
insert #Exec (ExecStr, orders)
values(@varKScStr3F_1, 1110)		
 
insert #Exec (ExecStr, orders)
values(@varKScStr3F, 1400)	

declare @cTMP varchar(8000), @itmp int
declare @cTMPF varchar(8000), @itmpF int

set @itmp = PATINDEX('%itog %', @varKSRunStr05)
set @cTMP = ''
if @itmp > 0
begin
	SET @cTMP = RIGHT(@varKSRunStr05, LEN(@varKSRunStr05) - @itmp + 4 )
	set @varKSRunStr05 = LEFT(@varKSRunStr05, @itmp - 4)
end

set @itmpF = PATINDEX('%itog %', @varKSRunStr05F)
set @cTMPF = ''
if @itmpF > 0
begin
	SET @cTMPF = RIGHT(@varKSRunStr05F, LEN(@varKSRunStr05F) - @itmpF + 4 )
	set @varKSRunStr05F = LEFT(@varKSRunStr05F, @itmpF - 4)
end

IF @iType=0
	begin
		declare @StatCodeForm varchar(100)
		select @StatCodeForm = RTRIM(RF.Code) + ' ' + LEFT(RT.Name, 40) from dbo.report_tables RT join dbo.report_forms RF on RT.link_form = RF.link_form
		where RT.link_table = @iLINK_TABLE
		set @varKSRunStr = 
'PROCEDURE ' + @varKSViewName + '
@varKSLSF	int,
@varKSpTYPE	int=1,
@varKSPNom	int=1,
@varKSpDATE	datetime=''01/01/2003'',
@varKScCodeRow	varchar(100)='''',
@iLINK_SAVED_FORM INT = NULL,
@bDeleteEmptyRows BIT = NULL,
@tmp_table varchar(100) = '''',
@del_fcol int=0,
@all_str int=0
AS
declare @Reads int , @time_begin datetime
set @time_begin = getdate()
--  Генератор I_REPORT_CREATE_PROC
if exists(select * from report_saved_forms where link_saved_form=@varKSLSF and is_arhiv=1) 
	exec '+@varKSViewName+'_ARH @varKSLSF,@varKSpTYPE,@varKSPNom,@varKSpDATE,@varKScCodeRow,@iLINK_SAVED_FORM,@bDeleteEmptyRows,@tmp_table,@del_fcol,@all_str
else	
	exec '+@varKSViewName+'_OPER @varKSLSF,@varKSpTYPE,@varKSPNom,@varKSpDATE,@varKScCodeRow,@iLINK_SAVED_FORM,@bDeleteEmptyRows,@tmp_table,@del_fcol,@all_str
	set @Reads = @@ROWCOUNT
--	if ISNULL((select Val_Int from dbo.report_options where razdel = ''statistics'' and code = ''mode''), 0) = 1 
--		insert dbo.report_statistics (Operation, CodeForm, Reads, Duration) values (4, ''' + @StatCodeForm + ''', @Reads,  getdate() - @time_begin)
'
	
	IF Object_id (@varKSViewName) is not null
	    BEGIN
		  	execute('ALTER ' + @varKSRunStr)
    	END   
   ELSE
  		execute('CREATE ' + @varKSRunStr )
	set @varKSRunStr = 'GRANT EXECUTE ON ' + @varKSViewName + ' TO PUBLIC'

	EXECUTE (@varKSRunStr)
    exec I_REPORT_CREATE_PROC @iLINK_TABLE,'',1
	exec I_REPORT_CREATE_PROC @iLINK_TABLE,'',2
	exec I_REPORT_CREATE_PROC @iLINK_TABLE,'#',3
	end
else
begin
	IF Object_id (@varKSViewName) is not null
   BEGIN
		insert #Exec (ExecStr, orders)
		values('ALTER ', 0)	
   END   
   ELSE
		insert #Exec (ExecStr, orders)
		values('CREATE ', 0)	

	exec ssp_execresultset 'select ExecStr from #Exec order by orders'

	set @varKSRunStr = 'GRANT EXECUTE ON ' + @varKSViewName + ' TO PUBLIC'
--	print @varKSRunStr
	EXECUTE (@varKSRunStr)
end
	set @varKSViewName = replace(@varKSViewName, 'dbo.', '')
	exec dbo.U_UPDATE_SCRIPT_PROPERTY @varKSViewName, 1, 'NOSCRIPT'

	drop table #Exec
END


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

/*
exec RI_PROC_T1867 5.768000000000000e+003
dbo.[I_REPORT_CREATE_PROC] 1867

select * from report_saved_forms 
select * from report_tables where link_form = 640

I_REPORT_CREATE_PROC_ON_SETUP

*/
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 [GUID]	= '', 	
	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
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_EXPORT_ZKR_16]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.BB_EXPORT_ZKR_16

GO


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

CREATE PROCEDURE dbo.BB_EXPORT_ZKR_16
	@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,
	@iSguDop 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 @iSguDop = dbo.sa_get_option_by_code('BB_ZAYAVKA_KR_OPTIONS_SGU_DOP')

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.KBK_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 = isnull(rtrim(case when left(DA.CODE,2) = '21' or left(DA.CODE,2) = '31' then isnull(ZT.DCL_CODE, '-') else ZT.DCL_CODE end), '') + case when @iSguDop = 1 and isnull(ZT.SGU_CODE, '') <> '' then '(' + rtrim(ZT.SGU_CODE) + ')'  else '' 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_16 TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
c Кейсистемс (Keysystems), 2006
Расчет итогов для отчета (досчет), формулы берутся из КС
20060817 доступ к колонке
*/
CREATE              PROCEDURE dbo.RO_CALCULATE_DOSCHET
  @LSF  int,
  @cTables varchar(1000) = '',
  @cProgressTable     varchar(254)  = ''
AS

EXEC RN_CALCULATE_DOSCHET @LSF,@cTables,@cProgressTable
return 
declare @LinkForm int, @linkRule int, @ExecProc varchar(300), @OrderRow int, @ordersRule int, @i int,@nprecision float(10)
set @nprecision=0.001

select @LinkForm = Link_Form from dbo.report_saved_forms where Link_Saved_Form = @LSF
if @LinkForm is NULL
  return  -1

create table #Rules (link_rule int, order_rule int)
--declare @t_KS table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(100), Factor float(53), Exec_Proc varchar(250), Exec_Proc_Desc varchar(250), Value float(53), orders varchar(250))
declare @t_KS_V table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(100), [Rows] varchar(250), Cols varchar(250), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Filter varchar(250), Mask varchar(250), Value float(53), orders varchar(250), Filter_Desc varchar(250), Mask_Desc varchar(250),isLeftPart int) 
declare @t_temp table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(100), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value float (53), orders varchar(250))
declare @t_tmp table (lc int, lr int, lrule int, V float(53), o varchar(250), s char(2), cr varchar(100))
create table #t_sum (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(100), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value float (53), orders varchar(250))
create table #t_znak_not_plus (Link_Rule int, Orders varchar(250))
--create table  @t_Col table (Link_Col int primary key, Name varchar(254), Link_Table int, Val_Len tinyint)

create table #t_KS (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(100), [Rows] varchar(250), Cols varchar(250), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Filter varchar(250), Mask varchar(250), Value float(53), orders varchar(250), Filter_Desc varchar(250), Mask_Desc varchar(250),isLeftPart int ) 
create table #t_Col (Link_Col int primary key, Name varchar(254), Link_Table int, Val_Len tinyint, OrderCol tinyint)
create table #ListForms (lsf int, linkForm int, codeForm char(20), startDate datetime)

declare @strProgressExec varchar(1000)

insert #ListForms
    select link_saved_form, link_form, '', NULL from report_saved_forms where  Link_saved_form = @LSF 


select *
INTO #REPORT_FORMS
from REPORT_FORMS WITH (NOLOCK)
where link_form = (select linkform from #ListForms)



select *
into #report_tables
from dbo.report_tables WITH (NOLOCK)
where link_form in (select link_form from #REPORT_FORMS)

select *
into #REPORT_COLOUMNS
from dbo.REPORT_COLOUMNS WITH (NOLOCK)
where link_table in (select link_table from #report_tables)


if (select Code from #report_forms where Link_Form = @LinkForm) like '428%'
begin
  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000120', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000120' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000151', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000151' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00085000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00085000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00079000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00079000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00096000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00096000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000000' and Link_SF = @LSF)


  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00090000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00090000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00050000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00050000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00070000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00070000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000710', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000710' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000810', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000810' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000500', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000500' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000600', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000600' and Link_SF = @LSF)

end

if (select Code from #report_forms where Link_Form = @LinkForm) like '428'
begin
  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000251', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000251' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000540', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000540' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000640', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000640' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000231', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000231' and Link_SF = @LSF)
end 

-- колонки, которые можно загрузить из справочника, для динамических таблиц

IF @cTables=''
BEGIN
        declare cur_Table cursor local static forward_only
        for select orders from #report_tables where Link_Form = @LinkForm and Val_Type = 1
END
ELSE
BEGIN
        declare cur_Table cursor local static forward_only
        for select orders from #report_tables rt where rt.Link_Form = @LinkForm and rt.Val_Type = 1 and exists(select * from #iTables IT where IT.link_Table=rt.Link_table)
END
declare @OrderTable int 

open cur_Table
fetch next from cur_Table
into @OrderTable

while @@fetch_status = 0
begin
  exec dbo.RO_IMPORT_WITH_DICT @LSF, @orderTable
  fetch next from cur_Table
  into @OrderTable
end

close cur_Table
deallocate cur_Table

SELECT RR.*,RSV.Formula code 
into #I_REPORT_ROWS
FROM Report_Rows RR WITH (NOLOCK) LEFT JOIN 
  Report_Formula  RSV WITH (NOLOCK)
    ON  link_col IN (select link_code_col from #report_tables)
        AND RSV.link_row=RR.link_row
where link_table in (select link_table from #report_tables)

select *
into #i_report_dinamic_rows
from dbo.i_report_dinamic_rows WITH (NOLOCK)
where link_SF in (select lsf from #ListForms)

select *
into #REPORT_CONTROL_RULES
From REPORT_CONTROL_RULES WITH (NOLOCK)
where link_form in (select link_form from #REPORT_FORMS)

select *
into #REPORT_SUMMA
From REPORT_SUMMA WITH (NOLOCK)
Where Link_Saved_Form in (select lsf from #ListForms) AND Summa<>0

select *
into #REPORT_DINAMICS
From REPORT_DINAMICS WITH (NOLOCK)
Where Link_SF in (select lsf from #ListForms) and Float_val<>0


if (select Code from #report_forms where Link_Form = @LinkForm) like '428%'
begin
  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000120', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000120' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000151', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000151' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00085000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00085000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00079000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00079000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00096000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00096000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000000' and Link_SF = @LSF)


  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00090000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00090000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00050000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00050000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00070000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00070000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000710', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000710' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000810', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000810' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000500', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000500' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000600', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000600' and Link_SF = @LSF)

end

if (select Code from #report_forms where Link_Form = @LinkForm) like '428'
begin
  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000251', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000251' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000540', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000540' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000640', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000640' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000231', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000231' and Link_SF = @LSF)
end 

  insert #t_Col (Link_Col, Name, Link_Table, Val_Len, OrderCol)
      select RC.Link_Col, RC.Name, RC.Link_Table, RC.Val_Len, RC.orders
      from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table and RC.Col_Type = 0
      inner join #ListForms LF on RT.Link_Form = LF.LinkForm


if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Получение списка правил для формы'', percents = 10'
    execute(@strProgressExec)
end

-- получаем правила
insert into #Rules exec dbo.I_CONTROL_RULES_LIST @LSF, 0,default,default,default,1
declare @t_Rules table (Link_Rule int)

--insert @t_Rules
--select Link_Rule from #report_control_rows Ro left join #i_report_dinamic_rows RD on RD.Link_SF = @LSF and Ro.Code_Row = RD.Code_Row and RD.Link_Table = Ro.Link_Table
--    where Val_Type < 3 or RD.Code_Row is not NULL or RTRIM(ISNULL(Ro.Code_Row,'')) = '' or [sign] = '^'
--select * from @t_Rules
--return 

Create index #IX_REPORT_SUMMA on #report_summa (link_col,link_row)
Create index #IX_T_KS on #T_KS (link_rule,orders)
Create index #IX_T_KS_ORDERROW on #T_KS (ORDERROW)
Create index #IX_report_dinamics on #report_dinamics (link_sf,code_row,link_col)



declare @link_form int
select  @link_form=linkform from #ListForms
declare @minDateUpdCache datetime,@maxDateModifyRule datetime
select  @minDateUpdCache=Min(Upd_date) FROM REPORT_CONTROL_ROWS_CACHE RC WITH (NOLOCK) WHERE Link_Rule in (select link_rule from #Rules)
set     @minDateUpdCache=isnull(@minDateUpdCache,'19900101')
select  @maxDateModifyRule=Max(Modify_Date) from #Report_control_rules

--если данные в кеше старые или их нет, обновим их
IF @minDateUpdCache<@maxDateModifyRule and not EXISTS(select * from JURNAL where tableName='KS_REFRESH_CASH' and  link_pk=@link_form)
        exec RN_KS_REFRESH_CASH @link_form

IF EXISTS(SELECT  link_rule FROM REPORT_CONTROL_ROWS_CACHE RC WITH (NOLOCK)
                   WHERE Link_Rule in (select link_rule from #Rules) and IsDoschet = 1)  AND not EXISTS(select * from JURNAL where tableName='KS_REFRESH_CASH' and  link_pk=@link_form)
BEGIN
--есть данные в кеш таблице. 
declare  @NRULES table  (Link_Rule int,Orders varchar(100),include int)
INSERT @NRULES
    SELECT Link_rule,orders,sum(
        case when RC.val_type in (1,4) then 1
             when RC.Exec_proc<>'' then 1
             else 0 end)      
        FROM REPORT_CONTROL_ROWS_CACHE RC WITH (NOLOCK)
        WHERE Link_Rule IN (select link_rule from #Rules) and IsDoschet = 1 Group By Link_Rule,orders

declare  @NRULES1 table  (Link_Rule int,Orders varchar(100),orderrule int,[ROWS] varchar (250))


INSERT @NRULES1 
        SELECT A.Link_Rule,A.Orders,B.orderrule,B.[rows] 
        FROM @NRULES A LEFT JOIN #REPORT_CONTROL_RULES B on A.link_rule=B.link_Rule
--        WHERE   include>0 or 
--                   EXISTS(select * from #report_summa RS,REPORT_CONTROL_ROWS_CACHE   RRC with (nolock) where RRC.link_rule=A.link_rule and RRC.orders=A.orders and RS.link_col=RRC.link_col and RS.link_Row=RRC.link_Row)  
--                OR EXISTS(select * from #report_dinamics RS,REPORT_CONTROL_ROWS_CACHE RRC with (nolock) where RRC.link_rule=A.link_rule and RRC.orders=A.orders  and RS.link_col=RRC.link_col )                       

INSERT #T_KS
    SELECT 
            RC.Link_Rule, RC.Calc_Orders, RC.OrderRow, RC.Val_Type, RC.SignAfter, RC.Link_Table, RC.Link_Col, RC.Link_Row, RTRIM(isnull(RC.Code_Row,'')), CASE when RT.val_type=0 then '' else A.[ROWS] end, '', RC.Factor, RC.Exec_Proc, RC.Exec_Proc_Desc, RC.Filter, RC.Maska, 0, RC.Orders, RC.Filter_Desc, RC.Maska_Desc,isLeftPart
        FROM @NRULES1 A,REPORT_CONTROL_ROWS_CACHE RC WITH (NOLOCK) LEFT JOIN REPORT_TABLES  RT (nolock) ON RC.link_table=RT.link_table
        WHERE RC.Link_Rule=A.Link_Rule AND RC.orders=A.orders


 --если досчитываем одну таблицу отчета - удаляем лишние правила     
  IF @cTables<>'' 
   DELETE FROM #t_KS WHERE Link_Rule in (SELECT Link_Rule FROM #t_KS TK WHERE not exists(select * from #iTables IT where TK.linkTable=IT.Link_table) and  TK.LinkTable is not NULL and TK.orderrow=1)

--для динамических таблиц, необходимо размножение по строкам
        IF EXISTS(select  RT.link_Table from #report_tables RT,#t_Col TC where RT.link_table=TC.link_table and RT.val_type=1)
            begin
                if @cProgressTable <>'' begin
                    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Размножение правил'', percents = 30'
                    execute(@strProgressExec)
                end
                exec dbo.RO_RAZMNOJ_KS 1 -- размножаем правила
            end
END
ELSE
BEGIN
        select *
        into #REPORT_CONTROL_ROWS
        From REPORT_CONTROL_ROWS WITH (NOLOCK)
        where link_form in (select link_form from #REPORT_FORMS)

        insert  #t_KS
        SELECT R1.Link_Rule, Calc_Orders, OrderRow, Val_Type, Sign, Link_Table, Link_Col, Link_Row, RTRIM(isnull(Code_Row,'')), R1.[Rows], R1.[Cols], Factor, Exec_Proc, Exec_Proc_Desc, R2.Filter, R2.Maska, 0, '', Filter_Desc, Maska_Desc,-1
        FROM #REPORT_CONTROL_RULES R1 left join #REPORT_CONTROL_ROWS R2 on r1.Link_Rule = r2.Link_Rule
        WHERE R1.Link_Rule in (select link_rule from #Rules) and IsDoschet = 1 

 --если досчитываем одну таблицу отчета - удаляем лишние правила     
  IF @cTables<>'' 
   DELETE FROM #t_KS WHERE Link_Rule in (SELECT Link_Rule FROM #t_KS TK WHERE not exists(select * from #iTables IT where TK.linkTable=IT.Link_table) and  TK.LinkTable is not NULL and TK.orderrow=1)

                if @cProgressTable <>'' begin
                    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Размножение правил'', percents = 30'
                    execute(@strProgressExec)
                end

   exec dbo.RO_RAZMNOJ_KS 1 -- размножаем правила


END
-- доступ по колонке
--delete #t_KS
--where Link_Rule in (select Link_Rule from #t_KS where OrderRow = 1 and LinkCol is NOT NULL and dbo.RO_AccessColByLink(LinkCol) <= 0)

--select * from #T_KS A where exists
--(select * from #t_ks B where B.coderow='20205600080000151' and B.orderrow=1 and B.link_rule=A.link_rule and B.orders=A.orders)
--order by link_rule,orders,coderow
--return 
if not exists(select count(*) from #t_KS)
begin
  return  0
end
--select * from #t_ks where link_rule=371040
--индексы
--удалим все ненужные правила. 
--delete from #t_ks 

if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Подготовка к вычислению'', percents = 35'
    execute(@strProgressExec)
end


-- подготовка к вычислению
declare @t_znak table (LinkR int, OrderRule int, ord varchar(250), LC int, LR int, CR varchar(100), ValType tinyint)
declare @t_minus table (Link_Rule int)
declare @t_summa table (LinkR int, ord varchar (250), summa float(53))
declare @t_Result table (LC int, LR int, s float(53), CR varchar(100), ValType tinyint)
declare @OrderRule int
create table #Val (val float(53))



insert @t_znak (LinkR, OrderRule, ord, LC, LR, CR, ValType)
  SELECT Link_Rule, OrderRule, orders, LinkCol, LinkRow, CodeRow, Val_Type
  FROM #t_KS B
  WHERE [sign] = '='

delete #t_KS
where [sign] = '='

delete #report_summa
from @t_Znak
where Link_Saved_Form = @LSF and Link_Col = LC and Link_Row = LR and ValType = 0

delete #report_dinamics
from @t_Znak where Link_SF = @LSF and Link_Col = LC and Code_Row = CR and ValType = 3

select distinct LC,LR,CR,ValType into #t_znakTMP from @t_znak 

-- левые части приравниваем нулю
update report_summa
set Summa = 0
from #t_ZnakTMP
where Link_Saved_Form = @LSF and Link_Col = LC and Link_Row = LR and ValType = 0

update report_dinamics
set Float_Val = 0
from #t_ZnakTMP
where Link_SF = @LSF and Link_Col = LC and Code_Row = CR and ValType = 3
--для простых правил используем быстрое вычисление.
  
--select * from #t_ks
--select * from #t_ks where sign not in ('+','-','=')  or  val_type in (2)

if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Расчет итогов'', percents = 40'
    execute(@strProgressExec)
end

--SELECT * FROM #t_znakTMP WHERE cr='20000000000000000' ORDER BY lc

IF not EXISTS(select * from #t_ks where sign not in ('+','-','=') or  val_type in (2))  
begin
   --добавим итоговые ячейки в report_summa, report_dinamics
        insert #report_summa
          SELECT DISTINCT @LSF,LC,LR,0
          FROM #t_znakTMP where valType=0
        insert #report_dinamics
          SELECT DISTINCT @LSF,LC,CR,0,''
          FROM #t_znakTMP where valType=3
   --сдвиг  знаков 
--SELECT * FROM  #report_dinamics WHERE CODE_ROW='20000000000000000' ORDER BY CODE_ROW

   insert @t_minus
   select distinct link_rule from #t_ks where sign in ('-')

select link_rule,orderrow,sign into #sign FROM #T_KS A 
    where Exists(select * from @t_minus E where E.link_rule=A.link_rule) group by link_rule,orderrow,sign 

update #t_ks
    set [sign]=isnull(A.SIGN,'+')
    FROM   #T_KS D LEFT HASH JOIN #SIGN  A ON A.link_rule=D.link_rule AND  D.OrderRow = A.OrderRow +1 
    where Exists(select * from @t_minus E where E.link_rule=D.link_rule)

--   UPDATE #T_KS
--   SET [sign] = case when E.sign not in ('+','-') then '+' else E.sign end 
--    from #T_KS A,(select distinct isnull((select top 1 sign  from #t_ks C where A.link_rule=C.link_rule and A.orderrow-1=C.orderrow),'+')  sign  ,     
--             link_rule,orderrow FROM #T_KS A  where exists (select * from @t_minus B where B.link_rule=A.link_rule and A.orderrow in (B.orderRow,B.orderRow+1))) E
--           where A.link_rule=E.link_rule and A.orderrow=E.orderrow

     

--для констан проставим lin_col,link_row
--select * from #t_ks order by link_rule
   create table #value (link_rule int,orders varchar(100),Nsumma float(53))


--select * from #value where coderow='20205600080000151'
--select C.* from #t_ks where exists( C LEFT JOIN @T_ZNAK D ON C.Link_rule=D.linkR AND C.orders=D.ord
--        where  C.Nsumma<>0 and D.CR='20205600080000151'

   UPDATE #T_KS
       SET  linkcol=(select top 1 LC from @t_znak where  valtype in (0,3)) , linkrow=(select top 1 LR from @t_znak where valtype in (0)),codeRow=(select top 1 CR from @t_znak where valtype in (3))
       WHERE #T_KS.val_type=1 
--   вычисляем     
     Declare @CalcOrders int,@li int, @maxI int
     declare @t_order table (linkOrder int identity(1,1),OrderRule int)
     INSERT @t_order
     select  distinct OrderRule from #t_ks order by OrderRule 
     set @maxI=@@ROWCOUNT
     set @li=1    
        
     WHILE @li<=@maxI
     BEGIN
       select  @CalcOrders =OrderRule from @t_order where linkOrder=@li
       delete from #value 
    
   Insert #value 
    select Link_rule,orders,sum(nsumma) nsumma from 
        (select A.Link_rule,A.orders,
        NSumma = SUM(
       CASE WHEN A.[sign] = '+' and  val_type=0 THEN RS.Summa 
            WHEN A.[sign] = '-' and  val_type=0 THEN -RS.Summa 
            WHEN A.[sign] = '+' and  val_type=1 THEN A.Factor
            WHEN A.[sign] = '-' and  val_type=1 THEN -A.Factor
              ELSE 0 END)
                from #report_summa RS LEFT HASH JOIN #T_KS A ON 
                        RS.link_col=A.linkcol and RS.link_row=A.linkrow and A.val_type in (0,1) and A.OrderRule=@calcOrders 
                        where RS.summa<>0
                group by link_rule,orders        
         union all
        select A.Link_rule,A.orders,
        NSumma = SUM(
       CASE WHEN A.[sign] = '+' THEN RS.Float_val
            WHEN A.[sign] = '-' THEN -RS.Float_val
            WHEN A.[sign] = '+' and  A.val_type=1 THEN A.Factor
            WHEN A.[sign] = '-' and  A.val_type=1 THEN -A.Factor
          ELSE 0 END)
                from #report_dinamics RS LEFT HASH JOIN #T_KS A ON 
                        RS.link_col=A.linkcol and RS.code_row=A.coderow and A.OrderRule=@calcOrders  and A.val_type in (3,1)
                        where RS.float_val<>0
                group by A.link_rule,A.orders) A Group by Link_rule,orders


    UPDATE #report_summa 
       SET [summa]=[NSUMMA]
        from (select * from #value) C LEFT JOIN @T_ZNAK D ON C.Link_rule=D.linkR AND C.orders=D.ord
       where C.Nsumma<>0 and #report_summa.link_col=D.LC and #report_summa.link_row=D.LR

        UPDATE #report_dinamics
        SET [Float_val]=[NSUMMA]
        from (select * from #value) C LEFT JOIN @T_ZNAK D ON C.Link_rule=D.linkR AND C.orders=D.ord
        where  C.Nsumma<>0 and #report_dinamics.link_col=D.LC and #report_dinamics.code_row=D.CR

        set @li=@li+1
--select * from #report_dinamics where code_ROW='0009600000000000000'
    end
end
-----------------конец вычислений простых правил
else
begin

select @OrderRule = min(OrderRule) from @t_znak

update #t_KS
set OrderRow = OrderRow - 1

update #t_KS
set Exec_Proc = 'exec dbo.' + RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,')',' '),'(',' '))) + ', ' + LTRIM(STR(@LSF))
where val_type = 2
while exists(select top 1 * from @t_znak)
begin
  insert @t_KS_V
  select * from #t_KS where OrderRule = @OrderRule
  -- ВЫЧИСЛЕНИЕ VALUE - ЛИБО ЯЧЕЙКА, ЛИБО КОНСТАНТА, ЛИБО РЕЗУЛЬТАТ ВЫПОЛНЕНИЯ ПРОЦЕДУРЫ
  update @t_KS_V
  set Value = case when Val_Type = 0 then isnull((select round(summa, Val_Len) from #report_summa RS left join #report_coloumns RC on RS.Link_Col = RC.Link_Col where Link_Saved_Form = @LSF and RS.link_Col = LinkCol and Link_Row = LinkRow),0) 
      when Val_Type = 1 then isnull(Factor, 0) 
      when Val_Type = 3 then isnull((select round(float_val, Val_Len) from #t_Col RC inner loop join #report_dinamics RD on RD.Link_Col = RC.Link_Col where Link_SF = @LSF and RD.Link_Col = LinkCol and Code_Row = CodeRow), 0)
    end
--  select * from @t_KS_V
  declare Cur1 cursor static local
    for select Link_Rule, OrderRow, Exec_Proc, orders from @t_KS_V where LEN(RTRIM(ISNULL(Exec_Proc, ''))) > 0 and Val_Type = 2
  open Cur1
  fetch next from Cur1
  into @linkRule, @OrderRow, @ExecProc, @ordersRule
  while @@fetch_status = 0
  begin
    insert #Val execute(@ExecProc)
    update @t_KS_V set Value = isnull(val,0) from #Val where Link_Rule = @LinkRule and OrderRow = @OrderRow and orders = @OrdersRule
    delete #Val
    fetch next from Cur1
    into @linkRule, @OrderRow, @ExecProc, @ordersRule
  end
  close Cur1
  deallocate Cur1
  ----------
  -- ВЫЧИСЛЕНИЕ ВЫРАЖЕНИЯ
  insert #t_znak_not_plus
  select distinct Link_Rule, orders
  from @t_KS_V B where sign <> '+'

  insert #t_sum
  select Link_Rule, OrderRule, 1 as OrderRow, 0 as Val_Type, '+' as Sign, NULL as LinkTable, NULL as LinkCol, NULL as LinkRow, '' as CodeRow, 0 as Factor, ' ' as Exec_Proc, ' ' as Exec_Proc_Desc, sum(Value) as Value, orders
  from @t_KS_V A
  where not exists(select * from #t_znak_not_plus B where A.link_rule = B.link_rule and A.orders = B.orders)
  group by link_rule, OrderRule, orders

  delete @t_KS_V
--  from @t_KS_V K inner hash join (select distinct Link_rule from #t_sum) S on K.Link_Rule = S.Link_Rule
  from @t_KS_V K inner hash join #t_sum S on K.Link_Rule = S.Link_Rule
-- where link_rule in (select distinct Link_rule from #t_sum)

  set @i = 2
  while exists(select top 1 * from @t_KS_V where OrderRow > 1)
  begin
    insert @t_tmp (lc, lr, lrule, V, o, s, cr)
    select linkCol as lc, LinkRow as lr, Link_Rule as lrule, Value  as V, orders as o, sign as s, CodeRow from @t_KS_V where orderRow = @i

    
  /*  select @LSF, linkCol, linkRow, lc, lr, Value, V, sign, CodeRow, cr
    from @t_KS_V, @t_tmp A
    where OrderRow = 1 and link_rule = A.lRule and A.o = orders
*/
    update @t_KS_V
    set Value = dbo.ro_condition_eval_rule(@LSF, linkCol, linkRow, lc, lr, Value, V, sign, CodeRow, cr,@nprecision), sign = s, linkCol = lc, linkRow = lr, CodeRow = cr
    from @t_tmp A
    where OrderRow = 1 and link_rule = A.lRule and A.o = orders

    delete @t_tmp
    delete @t_KS_V where OrderRow = @i
    set @i = @i + 1
  end
  
  insert @t_KS_V (Link_Rule,OrderRule,OrderRow,Val_Type,Sign,LinkTable,LinkCol,LinkRow,CodeRow,Factor,Exec_Proc,Exec_Proc_Desc,Value,orders)
  select Link_Rule,OrderRule,OrderRow,Val_Type,Sign,LinkTable,LinkCol,LinkRow,CodeRow,Factor,Exec_Proc,Exec_Proc_Desc,Value,orders  from #t_sum

--  select * from  @t_KS_V

  insert @t_Result
  select LC, LR, Value, CR, ValType
  from @t_KS_V S inner hash join @t_znak Z on Z.LinkR = S.Link_Rule and Z.ord = S.orders and Z.OrderRule = @OrderRule

--  select * from @t_Result

  delete @t_Result where S = 0

  insert #report_summa (Link_Saved_form, Link_Col, Link_Row, Summa)
    select @LSF, LC, LR, max(S)
    from @t_Result R
    where ValType = 0 and LC is not NULL and LR is not NULL and not exists(select * from #report_summa S where Link_Saved_Form = @LSF and Link_Col = LC and Link_Row = LR)
    group by LC, LR
  
  update #report_summa
  set summa = s
  from @t_Result
  where ValType = 0 and link_saved_form = @LSF and Link_Col = LC and Link_Row = LR

  insert #report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val,str_val)
    select @LSF, LC, CR, max(S),''
    from @t_Result R
    where ValType = 3 and LC is not NULL and isnull(CR, '') <> '' and not exists(select * from #report_dinamics S where Link_SF = @LSF and Link_Col = LC and Code_Row = CR)
    group by LC, CR

  update #report_dinamics
  set Float_val = s
  from @t_Result
  where ValType = 3 and link_SF = @LSF and Link_Col = LC and Code_Row = CR

  
  delete @t_Znak where OrderRule = @OrderRule
  delete @t_KS_V
  delete @t_Summa
  delete @t_Result
  delete #t_sum
  delete #t_znak_not_plus
  select @OrderRule = min(OrderRule) from @t_znak
end

drop table #Rules
drop table #Val
drop table #t_sum
drop table #t_znak_not_plus

end

--сохраним данные из временных табличек

INSERT report_summa
select distinct RS.* from #report_summa RS,#t_znakTMP TZ
where RS.Link_Saved_Form = @LSF and RS.Link_Col = TZ.LC and RS.Link_Row = TZ.LR and TZ.ValType = 0
      and not exists(select * from report_summa S where S.Link_Saved_Form = @LSF and Link_Col = TZ.LC and Link_Row = TZ.LR) AND RS.summa<>0

update report_summa
set Summa = RS.Summa
from #report_summa RS,#t_znakTMP TZ
where (RS.Link_Saved_Form = @LSF and RS.Link_Col = TZ.LC and RS.Link_Row = TZ.LR and TZ.ValType = 0) 
       and report_summa.Link_Saved_Form=RS.Link_saved_form and report_summa.Link_Col=RS.Link_Col and report_summa.Link_Row=RS.Link_Row and RS.summa <>0
---------
--select * from  #report_dinamics order by link_col,code_row
--select * from report_dinamics where Link_SF = @LSF

--select RS.* from #report_dinamics RS,#t_znakTMP TZ
--where RS.Link_SF = @LSF and RS.Link_Col = TZ.LC and RS.Code_Row = TZ.CR and TZ.ValType = 3
--       and not exists(select * from report_dinamics S where S.Link_SF = @LSF and Link_Col = TZ.LC and Code_Row = TZ.CR) and RS.float_val<>0

--select RS.link_col,rs.code_row,count(*) from #report_dinamics RS,#t_znakTMP TZ
--where RS.Link_SF = @LSF and RS.Link_Col = TZ.LC and RS.Code_Row = TZ.CR and TZ.ValType = 3 group by RS.link_col,rs.code_row having count(*)>1 
----------
INSERT report_dinamics
select distinct RS.* from #report_dinamics RS,#t_znakTMP TZ
where RS.Link_SF = @LSF and RS.Link_Col = TZ.LC and RS.Code_Row = TZ.CR and TZ.ValType = 3
       and not exists(select * from report_dinamics S where S.Link_SF = @LSF and Link_Col = TZ.LC and RTRIM(Code_Row) = RTRIM(TZ.CR)) and RS.float_val<>0


update report_dinamics
set float_val=RS.Float_Val
from #report_dinamics RS,#t_znakTMP TZ
where RS.Link_SF = @LSF and RS.Link_Col = TZ.LC and RS.Code_Row = TZ.CR and TZ.ValType = 3
      and report_dinamics.link_sf=RS.link_sf and report_dinamics.link_col=RS.link_col and RTRIM(report_dinamics.code_row)=RTRIM(rs.code_row)  and RS.float_val<>0


if (select Code from #report_forms where Link_Form = @LinkForm) like '428%'
begin
  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000120', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000120' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000151', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000151' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00085000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00085000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00079000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00079000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00096000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00096000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000000' and Link_SF = @LSF)


  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00090000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00090000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00050000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00050000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00070000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00070000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000710', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000710' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000810', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000810' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000500', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000500' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000600', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000600' and Link_SF = @LSF)

end

if (select Code from #report_forms where Link_Form = @LinkForm) like '428'
begin
  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000251', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000251' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000540', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000540' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000640', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000640' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000231', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000231' and Link_SF = @LSF)
end 

-- колонки, которые можно загрузить из справочника, для динамических таблиц
if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Завершение расчета итогов'', percents = 90'
    execute(@strProgressExec)
end

--IF @cTables=''
--BEGIN
        declare cur_Table cursor local static forward_only
        for select orders from #report_tables where Link_Form = @LinkForm and Val_Type = 1
--END
--ELSE
--BEGIN
--        declare cur_Table cursor local static forward_only
--        for select orders from #report_tables rt where rt.Link_Form = @LinkForm and rt.Val_Type = 1 and exists(select * from #iTables IT where IT.link_Table=rt.Link_table)
--END

open cur_Table
fetch next from cur_Table
into @OrderTable

while @@fetch_status = 0
begin
  exec dbo.RO_IMPORT_WITH_DICT @LSF, @orderTable
  fetch next from cur_Table
  into @OrderTable
end

close cur_Table
deallocate cur_Table


--EXEC dbo.[RA_CALCULATE_KS_OUTSIDE] @LSF
GO
GRANT ALL ON dbo.[RO_CALCULATE_DOSCHET] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*

	© Кейсистемс (Keysystems), 2006
	Редактирование/создание отчета/свода/свода сводов в WEB
*/

CREATE       PROCEDURE dbo.RN_SPLIT_CODE_ROW
    @lsf int, -- линк сохраненной формы
	@OrderTable tinyint = NULL -- порядковый номер таблицы
AS

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

   declare @code_form varchar(20),@link_form int,@date datetime, @linkTable_only int
   set @code_form=''
   select @date=start_date,@code_form=code,@link_form=link_form from report_forms where link_form=(select link_form from report_saved_forms where link_saved_form=@LSF)
   IF @code_form=''
		return
   --проведем расщепление code_row
   create table #code (link_col int,code_row varchar(100),str_val varchar(250)) 
   create table #tmp_code (link_col int,code_row varchar(100),str_val varchar(250)) 
   declare @link_col int,@link_table int,@script_str varchar(8000),@key varchar(1000),@i int,@count_col int,@cstr varchar(8000),@split varchar(1000)

	if @OrderTable is NOT NULL
		select @linkTable_only = Link_Table from report_tables where link_form = @link_form and orders = @OrderTable
   
   --сплит по новому	
   IF exists(select * from report_tables where link_form=@link_form and charindex('SPLIT=',script_str)>0) 
	begin
		--
		declare @table_split table (link_table int,script_str varchar(8000)) 
		insert @table_split
		select link_table,script_str from report_tables where link_form=@link_form and charindex('SPLIT=',script_str)>0 
			and (Link_Table = @linkTable_only or @OrderTable is NULL) -- добавлено Olga 2009.10.05 для импорта
		while exists(select * from @table_split)
			begin
				select top 1 @link_table=link_table,@script_str=script_str from @table_split
				exec rn_get_formula_code_row @link_Table,'SPLIT=',@key output
				--расшифровка
				set @key=replace(@key,'SPLIT=','')
				set @count_col=dbo.rn_getwordcount(@key,'#')
				set @i=1
				while @i<=@count_col
					begin
						set @split=dbo.rn_getwordnum(@key,@i,'#')
						select @link_col=link_col from report_coloumns where link_table=@link_table and orders=cast(replace(upper(dbo.rn_getwordnum(@split,1,'=')),'COL','') as int)
						--print @key
						--print @split
						set @split=replace(@split,dbo.rn_getwordnum(@split,1,'=')+'=','')
						set @cstr='insert #tmp_code (link_col,code_row,str_val)
						select distinct '+str(@link_col)+',code_row,'+@split+' from report_dinamics where link_sf='+str(@lsf)+' and link_col in (select link_col from report_coloumns where link_table='+str(@link_table)+')'
						--print @cstr
						SET @i=@i+1
						execute(@cstr)
					end
				delete  @table_split where link_table=@link_table
			end


	--запись данных
    Create index #IX_tmp_code_new on #tmp_code (link_col,code_row)

    INSERT report_dinamics (link_sf,link_col,code_row,str_val)
    select @lsf,link_col,code_row,str_val from #tmp_code A where not exists(select * from report_dinamics B where B.link_sf=@lsf and B.link_col=A.link_col and A.code_row=B.code_row) group by link_col,code_row,str_val

    UPDATE report_dinamics 
    SET str_val=A.str_val
    from report_dinamics B ,#tmp_code A where B.link_sf=@lsf and B.link_col=A.link_col and A.code_row=B.code_row 

	return
	end

   IF @code_form like '0503169%' or @code_form like '0503369%'
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1
        --счет
       select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',1,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)


        --год
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,REPLACE(REPLACE(SUBSTRING(RTRIM(CODE_ROW)+'',10,4),'8888',''),'0000','') from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 


   IF @code_form in ('(72н)0503317G','(72н)0503317M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=2
        --adm расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=5
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=6
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',8,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ВР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=7
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',15,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЭКР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=8
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',18,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
     end 


   IF @code_form in ('(72н)0503152','0503152G')
     begin
        ----------------------- расходы --------------------------------------------------------
		select @link_table=link_table from report_tables where link_form=@link_form and orders=2
        --adm расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=5
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',8,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ВР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=6
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',15,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЭКР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=7
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',18,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

		----------------------- источники ------------------------------------------------------
        select @link_table=link_table from report_tables where link_form=@link_form and orders=3
        --Код строки
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000000000000',4,20) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 


   IF @code_form in ('(72н)0503182M')
   BEGIN
      select @link_table=link_table from report_tables where link_form=@link_form and orders=3
      
      --Код строки
      select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
      insert #tmp_code (link_col,code_row,str_val)
      select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'000',1,3) 
      from report_dinamics 
      where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

      --Источники
      select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
      insert #tmp_code (link_col,code_row,str_val)
      select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
      
   
   END
   
   IF @code_form in ('(72н)0503317M','(72н)0503314M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=3
        --Код строки
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000000000000',4,20) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 

   IF @code_form in ('(72н)0503151','0503151G','(72н)0503124','(72н)0503127M','(72н)0503117M','(72н)0503137M','(72н)0503114M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=3
        --Код строки
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000000000000',4,17) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 

   IF @code_form = ('(72н)0503110')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1
        --adm 
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1 -- таблица доходы
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --Дохгр
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',4,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --код счета
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',7,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_table=link_table from report_tables where link_form=@link_form and orders=2 -- таблица расходы
        --adm 
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --РзПр
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --код счета
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',8,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_table=link_table from report_tables where link_form=@link_form and orders=3 -- таблица источники
        --adm 
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --РзПр
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --код счета
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',8,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
     end 


   IF @code_form in ('(72н)425M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1
        --adm 
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --okato
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'                               ',4,8) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --элемент бюджета
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'                                ',12,2) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --код счета
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=5
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'                                                       ',14,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --счет
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=8
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'                                                       ',23,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
     end 

   IF @code_form in ('РРО1')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'       ',1,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'         ',8,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=18
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'000',17,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
     end 

   IF @code_form in ('(90н)581')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1
        --код организации 
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'                ',6,10) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table) /*and Code_Row not like '_____ИТОГО%' */and Code_Row not like '_____ВСЕГО%'
    end

   IF @code_form in ('(72н)0503151','0503151G','(72н)0503124','(72н)0503117','(72н)0503127','(72н)0503137','(72н)0503114','(72н)0503117M','(72н)0503127M','(72н)0503137M','(72н)0503114M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=2

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',1,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',5,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ВР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=5
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',12,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЭКР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=6
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',15,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
     end 

   IF @code_form in ('(72н)0503164','(72н)0503179G','(72н)0503164M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=2

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',1,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',5,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 

   IF @code_form in ('(72н)0503179G')
   BEGIN     
        select @link_table=link_table from report_tables where link_form=@link_form and orders=3
         
        --Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000000000000',4,17) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
   END

   IF @code_form in ('(72н)0503364M','(72н)0503364Mf')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=2

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',1,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',5,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 



   IF @code_form in ('(72н)0503164M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=3

       --Код строки
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000000000000',4,8) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 




   IF @code_form in ('(72н)0521443') 
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1

        -- расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',1,20) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        -- расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',22,20) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 
                                                                                             
   IF @code_form like '(72н)0503169%' --or @code_form like '%0503369%' --or @code_form like '0503169G%'
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1

        --счет
       select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,REPLACE(SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',1,9),'888888888','Всего задолженности:') from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)


        --год
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,REPLACE(REPLACE(SUBSTRING(RTRIM(CODE_ROW)+'',10,4),'8888',''),'0000','') from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 


   IF @code_form like '(72н)410%'
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1
        -- Доходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',1,17) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',18,6) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',24,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_table=link_table from report_tables where link_form=@link_form and orders=2
        -- Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',1,17) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',18,6) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',24,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_table=link_table from report_tables where link_form=@link_form and orders=3
        -- Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',1,17) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',18,6) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',24,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)



     end 


   IF @code_form in ('(72н)0521429M','(72н)0521429')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=3
        --adm расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=5
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',8,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ВР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=6
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',15,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЭКР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=7
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',18,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)



        select @link_table=link_table from report_tables where link_form=@link_form and orders=4
        --adm расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=5
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',8,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ВР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=6
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',15,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЭКР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=7
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',18,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)


     end 


--запись данных
    Create index #IX_tmp_code on #tmp_code (link_col,code_row)
   


    INSERT report_dinamics (link_sf,link_col,code_row,str_val)
    select @lsf,link_col,code_row,str_val from #tmp_code A where not exists(select * from report_dinamics B where B.link_sf=@lsf and B.link_col=A.link_col and A.code_row=B.code_row) group by link_col,code_row,str_val

    UPDATE report_dinamics 
    SET str_val=A.str_val
    from report_dinamics B ,#tmp_code A where B.link_sf=@lsf and B.link_col=A.link_col and A.code_row=B.code_row 

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

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[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(20)
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(20)

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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
c Кейсистемс (Keysystems), 2006
Расчет итогов для отчета (досчет), формулы берутся из КС
20060817 доступ к колонке
*/
CREATE           PROCEDURE dbo.RO_CALCULATE_INSIDE
  @LSF  int,
  @cTables varchar(1000) = '',
  @cProgressTable     varchar(254)  = '',
  @isWeb int = 0
AS
------------------------------------------------------------------------------
-- правила:
create table #t_Rules (Link_Rule int, Calc_orders int, algorithm tinyint, [sign_sr] char(2), cols varchar(250), [rows] varchar(1000), Str_Rule varchar(8000),  Comment varchar(2000), OrderRule INT, IsDoschet tinyint)
create table #t_Rules_region (Link_Rule int, orderRule int)
-- члены правила, используется для вычисления выражения:
create table #t_Row_KS (Link_Rule int, Calc_Orders int, OrderRow int, val_type tinyint, [sign] char(2), Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(100), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(250), part tinyint, algorithm tinyint, cols varchar(250), [rows] varchar(1000), [Value] float, orderCol tinyint default 0, CodeRow varchar(254) default '',cOrderTable varchar(254), cOrderCol varchar(10), [property] tinyint)
-- члены правила, используется для вычисления выражения:
create table #t_KS (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(100), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(250), part tinyint, algorithm tinyint, cols varchar(250), [rows] varchar(1000), [Value] float, orderCol tinyint default 0, CodeRow varchar(254) default '',cOrderTable varchar(254), cOrderCol varchar(10), px_comment varchar(254) default '', [property] tinyint)
-- левая часть
create table #t_KS_Left (Link_Rule int, val_type tinyint, Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(100), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(250), orderCol tinyint, CodeRow varchar(254), algorithm tinyint, cols varchar(250), [rows] varchar(1000))
-- записываем результат левой и правой частей:
create table #t_Result_C([Value] float, Link_Rule int, orderCol tinyint, CodeRow varchar(100), Link_Table int, Link_Col int, Link_Row int)

-- результат хранимок (хотя в будущем этого не надо)
create table #tmp (Value float)
-- для протокола операнды
--create table #t_Res_summand (Link_Rule int, OrderRow int, [sign] char(2), Code_Row varchar(100), [Value] numeric(20,4), orderCol tinyint default 0, CodeRow varchar(254) default '')
-- для размножения сложных правил
declare @t_temp table (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(100), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(250), part tinyint, algorithm tinyint, cols varchar(250), [rows] varchar(1000), [Value] float, orderCol tinyint default 0, CodeRow varchar(254) default '', cOrderTable varchar(254), cOrderCol varchar(10), px_comment varchar(254) default '', [property] tinyint)

-- для ускорения, чтобы уменьшить количество записей и не обращаться к постоянным таблицам
create table #t_Col (Link_Col int primary key, Name varchar(254), Link_Table int, Val_Len int, OrderCol tinyint, cOrderCol varchar(10))
create table #t_Rows_Static(Link_Row int primary key, Code varchar(100), Link_Table int, orders int)
create table #report_dinamics(Link_SF int, Code_Row varchar(100), link_col int, float_val numeric(20,4), str_val varchar(8000), Link_Table int)
create table #t_Summa(LSF int, link_col int, link_row int, Code varchar(100), summa float)
create table #t_Factor (Link_Rule int, OrderRow int, [sign] char(2), part tinyint, factor float)
create table #report_tables (Link_Table int, orders tinyint, Name varchar(254), Val_Type tinyint, Link_Code_Col int, Link_Form int)
-- Дерево КБК 
create table #TreeKBK (Link int, Link_Self int, Code_Row varchar(100), Link_Table int, Calc tinyint, cOrderTable varchar(300))
create table #TreeExclude (Code VARCHAR(100), Link_COl INT)

Create index #IX_REPORT_SUMMA on #t_summa (link_col,link_row)
Create index #IX_report_dinamics on #report_dinamics (link_col,code_row)
Create index #IX_report_dinamics_link_sf on #report_dinamics (link_table, link_col)

declare @cOrg varchar(254), @cBudg varchar(254), @LinkRule int, @ExecStr nvarchar(max),@ExecStr1 nvarchar(max), @IsSvod tinyint, @atr_code varchar(254), @i int, @maxOrderRow int, @orderTable int 
declare @nprecision float, @lsf_tmp int, @strProgressExec nvarchar(4000), @LinkF int, @codeForm varchar(20), @time_begin datetime, @time_end datetime, @cPeriod varchar(100), @CalcOrders int, @MaxCalcOrders INT
DECLARE @CodeRow VARCHAR(100), @dBeginDate DATETIME 
set @nprecision = 0.01


if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Получение данных отчетов'', percents = 3'
    exec sp_executesql @strProgressExec
end

if @cTables = '-1'
	set @cTables = ''

-------------------------------------------------------------------------------------------------------
-- получение данных 
select @LinkF = Link_Form, @dBeginDate = begin_date from report_saved_forms where link_saved_form = @LSF

exec dbo.ro_get_tree_kbk @LinkF, @cTables, @LSF -- грузим дерево КБК

insert #report_tables (Link_Table, orders, Name, Val_Type, Link_Code_Col, Link_Form)
select Link_Table, orders, Name, Val_Type, Link_Code_Col, Link_Form
from report_tables (NOLOCK)
where Link_Form = @LinkF

select * into #report_coloumns 
from report_coloumns RC (NOLOCK)
where Link_Table in (select Link_Table from #report_tables)

insert #t_Col (Link_Col, Name, Link_Table, Val_Len, OrderCol, cOrderCol)
select Link_Col, Name, Link_Table, Val_len, orders, ''
from #report_coloumns RC 
where Col_Type = 0 and dbo.RO_AccessColByLink(RC.Link_COl) > 0
if @isWeb = 1
begin
	delete #t_Col
	where exists(select top 1 * from report_saved_forms_permissions A where A.lsf=@LSF and A.link_col = #t_Col.Link_Col)
end
insert #t_Rows_Static(Link_Row, Code, Link_Table, orders)
select Link_Row, Code, Link_Table, orders
from i_report_rows 
where Link_Table in (select Link_Table from #report_tables where Val_Type = 0)

insert #t_summa (lsf, link_col, link_row, code, summa)
select RS.link_saved_form, RS.link_col, RS.link_row, R.code, RS.summa
from (select * from report_summa (NOLOCK) where Link_Saved_Form = @LSF)	RS inner join #t_Rows_Static R on RS.Link_Row = R.Link_Row

insert #report_dinamics (Link_SF, Code_Row, link_col, float_val, str_val, Link_Table)
select RD.Link_SF, RD.Code_Row, RD.link_col, RD.float_val, RD.str_val, C.Link_Table
from report_dinamics RD (NOLOCK) inner join #report_coloumns C on RD.Link_Col = C.Link_Col
where RD.Link_SF = @LSF --and C.Col_Type = 0

if @cProgressTable <>'' begin
	set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Получение правил досчета'', percents = 5'
	exec sp_executesql @strProgressExec
end

------------------------------------------------------------------------------------
-- получение правил
insert #t_Rules_region exec dbo.[I_CONTROL_RULES_LIST] @LSF, 0

insert #t_Rules (Link_Rule, Calc_orders, algorithm, [sign_sr], cols, [rows], Str_Rule, Comment, OrderRule, IsDoschet) 
select Ru.Link_Rule, Ru.Calc_orders, algorithm, sign_sr, REPLACE(cols,' ', ''), [rows], Str_Rule, Comment, Ru.OrderRule, Ru.[IsDoschet]
from report_control_rules Ru  (NOLOCK) inner join #t_Rules_region R on Ru.Link_Rule = R.Link_Rule
where isDoschet&1=1 --and Ru.Link_Rule = 2357895

truncate table #t_Rules_region


insert #t_Row_KS (Link_Rule, Calc_orders, OrderRow, val_type, [sign], Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], cOrderTable, cOrderCol, [property])
select Ro.Link_Rule, Calc_orders, Ro.OrderRow, Ro.val_type, Ro.[sign], Ro.Link_Table, Ro.Link_Col, Ro.Link_Row, Ro.Code_Row, Ro.Factor, Ro.px, Ro.Exec_Proc, Ro.Filter, coalesce(Ro.Filter_desc, Ro.Filter, ''), Ro.Maska, Ro.part, Ru.algorithm, REPLACE(Ru.cols,'-',''), Ru.[rows], '', '', [property]
from report_control_rows Ro (NOLOCK) inner join #t_Rules Ru on Ro.Link_Rule = Ru.Link_Rule


delete #t_Row_KS
where Link_Rule in (select Link_Rule from #t_Row_KS where Link_Col is NOT NULL and part = 0 and Link_Col not in (select Link_Col from #t_Col))


DELETE #t_Row_KS 
WHERE Link_rule IN (SELECT  r.link_rule  FROM  #t_Row_KS r JOIN dbo.report_control_rows ro ON r.[Link_Rule] = ro.link_rule AND r.[OrderRow] = ro.[OrderRow]
                   WHERE @dBeginDate <> ISNULL(ro.begin_date, @dBeginDate) AND r.Val_type IN (0, 3,4))     


declare @a_count int -- для динамических запросов

exec sp_executesql N'select @count = count(*) from #iTables', 
                   N'@count int output', @count = @a_count output


if isnull( @a_count,0)>0
begin
	delete #t_Row_KS where part = 0 and not exists(select top 1 * from #iTables T where T.Link_Table = #t_Row_KS.Link_Table) and Link_Table is NOT NULL

	delete #t_Row_KS
	where part = 1 and not exists(select top 1 * from #t_Row_KS R1 where R1.part = 0 and #t_Row_KS.Link_Rule = R1.Link_Rule)
end


--if not exists(select top 1 * from #t_Row_KS) 
--begin
--	drop table #t_Col
--	drop table #t_KS
--	drop table #t_KS_Left
--	drop table #t_Row_KS
--	drop table #t_Rules
--	drop table #t_Result_C
--	drop table #t_Rows_Static
--	drop table #tmp
--	drop table #report_dinamics
--	drop table #t_Summa
--	drop table #report_tables
--	return 0
--end

--update #t_KS set algorithm = 0 where algorithm = 4

update #t_Row_KS
set Exec_Proc = 'exec dbo.' + RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,')',' '),'(',' ')))  + ', ' + LTRIM(STR(@LSF))
where val_type = 2
/*update #t_Row_KS
set Exec_Proc = RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,']',')'),'[','('))) 
where val_type = 2
*/
select @MaxCalcOrders = max(Calc_Orders), @CalcOrders = min(Calc_orders) from #t_Rules
set @CalcOrders = isnull(@CalcOrders,0)
set @MaxCalcOrders = isnull(@MaxCalcOrders,-1)
if  @CalcOrders > 100
	exec dbo.RO_Tree_KBK_doschet @LSF

while @CalcOrders <= @MaxCalcOrders
begin
	--SELECT @CalcOrders
	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Расчет итогов №' + STR(@CalcOrders) + ''', percents = ' + convert(varchar(10), 5 + convert(int, @CalcOrders*90/(@MaxCalcOrders + 1) ))
		exec sp_executesql @strProgressExec
	END

	if  @CalcOrders = 100
		exec dbo.RO_Tree_KBK_doschet @LSF

	insert #t_KS (Link_Rule, OrderRow, val_type, [sign], Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], [Value], orderCol, CodeRow,cOrderTable, cOrderCol, [property])
	select Link_Rule, OrderRow, val_type, [sign], Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], [Value], orderCol, CodeRow,cOrderTable, cOrderCol, [property]
	from #t_Row_KS
	where Calc_Orders = @CalcOrders

	set @CalcOrders = @CalcOrders + 1

	set @a_count = 0
	exec sp_executesql N'select @count = count(*) from #t_KS', 
                   N'@count int output', @count = @a_count output

	if isnull(@a_count,0) = 0
		continue

	set @a_count = 0
	exec sp_executesql N'select @count = count(*) from #t_KS where algorithm in (0, 9)', 
                   N'@count int output', @count = @a_count output

	-----------------------------------------------------------------------------------------
	if isnull(@a_count,0) > 0
		exec dbo.RO_RAZMNOJ_KS_INSIDE 1 -- размножение правил для фильтров и знака '^' и сложных правил
	------------------------------------------------------------------------------------------
	insert #t_KS_Left (Link_Rule, val_type, Link_Table, Link_Col, Link_Row, Code_Row, Filter, Filter_desc, Mask, orderCol, CodeRow, algorithm, cols, [rows])
	select Link_Rule, val_type, Link_Table, Link_Col, Link_Row, Code_Row, Filter, Filter_desc, Mask, orderCol, CodeRow, algorithm, cols, [rows]
	from #t_KS
	where part = 0


	delete #t_KS where part = 0 
	delete #t_KS where not exists (select Link_Rule from #t_KS_Left L where L.Link_Rule = #t_KS.Link_Rule and isnull(L.orderCol, 0) = isnull(#t_KS.orderCol, 0) and isnull(L.CodeRow,'') = isnull(#t_KS.CodeRow,''))


	-- 	вычисляем
	-- обнуляем простые правила 
	update #t_Summa
	set summa = 0
	from (select * from #t_KS_Left where algorithm = 1 and Val_Type = 0) K
	where #t_Summa.Link_Col = K.Link_Col and #t_Summa.Link_Row = K.Link_Row
	
	update #report_dinamics
	set float_val = 0
	from (select * from #t_KS_Left where algorithm = 1 and Val_Type = 3) K
	where #report_dinamics.Link_Col = K.Link_Col and #report_dinamics.Code_Row = K.Code_Row

	-- простое правило
	insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
	select sum(case Val_Type 
					when 0 then case [sign] -- статическая таблица
							when '+' then case when K.[property] & 2 = 0 then isnull(S.summa,0)*px else isnull(abs(S.summa),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(S.summa ,0)*px else -isnull(abs(S.summa),0)*px end
						end 
					when 3 then  case [sign] -- динамическая таблица
							when '+' then case when K.[property] & 2 = 0 then isnull(D.float_val,0)*px else isnull(abs(D.float_val),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(D.float_val, 0)*px else -isnull(abs(D.float_val), 0)*px end
						end 
					when 1 then  case [sign] -- константа
							when '+' then K.Factor
							else -K.Factor
						end 
					else 0
				end), K.Link_Rule, orderCol, CodeRow
	from #t_KS K left join #t_summa S on S.Link_Col = K.Link_Col and S.Link_Row = K.Link_Row
		left join #report_dinamics D on D.Link_Col = K.Link_Col and D.Code_Row = K.Code_Row
	where algorithm = 1 
	group by Link_Rule, orderCol, CodeRow

	-----------------------------------------------------------------------------------------------------
	-- правило размножения для диапозона колонок 
	-- обнуляем
	update #t_Summa
	set summa = 0
	from #t_Summa S inner join #t_Col RC on S.Link_Col = RC.Link_Col, (select * from #t_KS_Left where algorithm = 2 and Val_Type = 0) K
	where S.Link_Row = K.Link_Row and (charindex(',' + rtrim(ltrim(str(RC.orderCol))) + ',', ','+cols+',') > 0 or cols = '')
	
	update #report_dinamics
	set float_val = 0
	from #report_dinamics S inner join #t_Col RC on S.Link_Col = RC.Link_Col, (select * from #t_KS_Left where  algorithm = 2 and Val_Type = 3) K
	where S.Code_Row = K.Code_Row and (charindex(',' + rtrim(ltrim(str(RC.orderCol))) + ',', ','+cols+',') > 0 or cols = '') and S.Link_Table = K.Link_Table

	
	insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
	select  sum(case Val_Type 
					when 0 then case [sign] -- статическая таблица
							when '+' then case when K.[property] & 2 = 0 then isnull(S.summa,0)*px else isnull(abs(S.summa),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(S.summa ,0)*px else -isnull(abs(S.summa),0)*px end
						end 
					when 3 then  case [sign] -- динамическая таблица
							when '+' then case when K.[property] & 2 = 0 then isnull(D.float_val,0)*px else isnull(abs(D.float_val),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(D.float_val, 0)*px else -isnull(abs(D.float_val), 0)*px end
						end 
					when 1 then  case [sign] -- константа
							when '+' then K.Factor
							else -K.Factor
						end 
					else 0
				end), Link_Rule, RC.orderCol, CodeRow
	from #t_KS K left join #t_summa S on S.Link_Row = K.Link_Row
		left join #report_dinamics D on D.Link_Table = K.Link_Table and D.Code_Row = K.Code_Row
		inner join #t_Col RC on isnull(S.link_col, D.link_col) = RC.link_col
	where algorithm = 2 and (charindex(',' + rtrim(ltrim(str(RC.orderCol))) + ',', ','+cols+',') > 0 or cols = '') and RC.orderCol is NOT NULL
	group by Link_Rule, RC.orderCol, CodeRow



	--------------------------------------------------------------------------------------------------------
	-- правило размножения для всех строк 
	-- обнуляем
	update #t_Summa
	set summa = 0
	from #t_Summa S, (select * from #t_KS_Left where algorithm = 3 and Val_Type = 0) K
	where S.Link_Col = K.Link_Col
	
	update #report_dinamics
	set float_val = 0
	from #report_dinamics S, (select * from #t_KS_Left where algorithm = 3 and Val_Type = 3) K
	where S.Link_Col = K.Link_Col

	insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
	select  sum(case Val_Type 
					when 0 then case [sign] -- статическая таблица
							when '+' then case when K.[property] & 2 = 0 then isnull(S.summa,0)*px else isnull(abs(S.summa),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(S.summa ,0)*px else -isnull(abs(S.summa),0)*px end
						end 
					when 3 then  case [sign] -- динамическая таблица
							when '+' then case when K.[property] & 2 = 0 then isnull(D.float_val,0)*px else isnull(abs(D.float_val),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(D.float_val, 0)*px else -isnull(abs(D.float_val), 0)*px end
						end 
				end), Link_Rule, orderCol, coalesce(S.Code, D.Code_Row, '')
	from #t_KS K left join #t_summa S on S.Link_Col = K.Link_Col
		left join #report_dinamics D on D.Link_Col = K.Link_Col and D.Link_Table = K.Link_Table
	where algorithm = 3 and not (S.Code is NULL and D.Code_Row is NULL)
	group by Link_Rule, orderCol, coalesce(S.Code, D.Code_Row, '')
	--having coalesce(S.Code, D.Code_Row, '') <> ''

	update #t_Result_C
	set Value = Value + F
	from (select Link_Rule as LR, sum(case when sign = '+' then Factor else -Factor end) as F from  #t_KS where algorithm = 3 and Val_Type = 1 group by Link_Rule) A
	where Link_Rule = LR

	insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
	select sum(case when sign = '+' then Factor else -Factor end), K.Link_Rule, K.orderCol, coalesce(S.Code, D.Code_Row, '')
	from #t_KS K join #t_KS_Left L on K.Link_Rule = L.Link_Rule
		left join #t_Rows_Static S on S.Link_Table = L.Link_Table
		left join (select distinct Code_Row, Link_Table from #report_dinamics) D on D.Link_Table = L.Link_Table	
	where K.algorithm = 3 and K.Val_Type = 1 and not exists(select top 1 * from #t_Result_C C where C.Link_Rule = K.Link_Rule)
	group by K.Link_Rule, K.orderCol, coalesce(S.Code, D.Code_Row, '')

	delete #t_KS
	where algorithm in (1, 2, 3)	
	-------------------------------------------------------------------------------------------
	-- диапозон строк 

	set @a_count = 0
	exec sp_executesql N'select @count = count(*) from #t_KS where algorithm  = 4', 
                   N'@count int output', @count = @a_count OUTPUT


	while isnull(@a_count,0) > 0 --and (@i < 2)
	begin
		set @i = @i + 1
		select top 1 @LinkRule = Link_Rule,  @ExecStr = 'update #t_Summa set summa = 0
	from #t_Summa S, (select * from #t_KS_Left where Link_Rule = ' + STR(Link_Rule) + ' and Val_Type = 0) K
	where S.Link_Col = K.Link_Col and (' + REPLACE([rows], 'COL(',  '(select case when col_type = 0 then STR((select summa from #t_summa B where B.Link_col = RC.link_col and S.Link_Row = B.Link_Row), 20,4) else (select formula from report_formula F where F.link_col = RC.link_col and F.link_row = S.Link_Row) end from report_coloumns RC where link_table = K.LINK_TABLE and orders =') +  ')
	update #report_dinamics set float_val = 0 from #report_dinamics RD, (select * from #t_KS_Left where Link_Rule = ' + STR(Link_Rule) + ' and Val_Type = 3) K
	where RD.Link_Col = K.Link_Col  and (' + REPLACE(REPLACE([rows],'CODE', 'RD.Code_Row'), 'COL(', '(select top 1 case when RC.Col_Type = 0 then LTRIM(STR(float_val,20,2)) else str_val end from #report_dinamics  RF (nolock) inner join report_coloumns RC on RF.Link_sf = RD.Link_SF and RF.Link_Col = RC.Link_Col   and RF.Code_Row = RD.Code_Row and RC.Link_Table = K.Link_Table and RC.orders =') + ')
	insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
	select  sum(case K.Val_Type 
					when 0 then case [sign] -- статическая таблица
							when ''+'' then case when K.[property] & 2 = 0 then isnull(S.summa,0)*px else isnull(abs(S.summa),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(S.summa ,0)*px else -isnull(abs(S.summa),0)*px end
						end 
					when 1 then  case [sign] -- константа
							when ''+'' then K.Factor
							else -K.Factor
						end 
					else 0
				end), K.Link_Rule, K.orderCol, S.Code
	from (select * from #t_KS where Link_Rule = ' + STR(Link_Rule) + ') K
         inner join #t_summa S on S.Link_Col = K.Link_Col  
	where ' + REPLACE([rows], 'COL(', '(select case when col_type = 0 then STR((select summa from #t_summa B where B.Link_col = RC.link_col and S.Link_Row = B.Link_Row), 20,4) else (select formula from report_formula F where F.link_col = RC.link_col and F.link_row = S.Link_Row) end from report_coloumns RC where link_table = K.LINK_TABLE and orders =') +  '
	group by K.Link_Rule, K.orderCol, S.Code
	having  S.Code <> ''''',
    @ExecStr1 = 'insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
	select sum(case K.Val_Type 
					when 3 then  case [sign] -- динамическая таблица
							when ''+'' then case when K.[property] & 2 = 0 then isnull(RD1.float_val,0)*px else isnull(abs(RD1.float_val),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(RD1.float_val, 0)*px else -isnull(abs(RD1.float_val), 0)*px end
						end 
					when 1 then  case [sign] -- константа
							when ''+'' then K.Factor
							else -K.Factor
						end 
					else 0
				end),  K.Link_Rule, K.orderCol, RD.Code_Row
	from #t_KS K
         inner join #t_KS_LEFT L on K.Link_Rule = L.Link_Rule  
         inner join (select distinct Link_SF, Link_Table, Code_Row from #report_dinamics) RD on K.Link_Table = RD.Link_Table or (K.Val_Type = 1 and RD.Link_Table = L.Link_Table)
         left join #report_dinamics RD1 on RD1.Link_Col = K.Link_Col and K.Link_Table = RD1.Link_Table and RD.Code_Row = RD1.Code_Row  
	where K.Link_Rule = ' + STR(Link_Rule) + ' and (' + REPLACE(REPLACE([rows],'CODE', 'RD.Code_Row'), 'COL(', '(select top 1 case when RC.Col_Type = 0 then LTRIM(STR(float_val,20,2)) else str_val end from #report_dinamics  RF (nolock) inner join report_coloumns RC on RF.Link_sf = RD.Link_SF and RF.Link_Col = RC.Link_Col   and RF.Code_Row = RD.Code_Row and RC.Link_Table = isnull(K.Link_Table,L.Link_Table) and RC.orders =') + ')
	group by K.Link_Rule, K.orderCol, RD.Code_Row
	having RD.Code_Row <> '''''
		from #t_KS
		where algorithm = 4 
		print @ExecStr
		print @ExecStr1
		exec sp_executesql @ExecStr, N'@LSF int', @LSF = @LSF
		exec sp_executesql @ExecStr1, N'@LSF int', @LSF = @LSF
		delete #t_KS where Link_Rule = @LinkRule 
		set @a_count = 0
		exec sp_executesql N'select @count = count(*) from #t_KS where algorithm  = 4', 
					   N'@count int output', @count = @a_count output
	end


	-------------------------------------------------------------------------------------------
	-- хранимки - теперь только одна хранимка в одном правиле!!!
	set @a_count = 0
	exec sp_executesql N'select @count = count(*) from #t_KS where algorithm  = 9 and Val_Type = 2', 
                   N'@count int output', @count = @a_count OUTPUT


	while isnull(@a_count,0) > 0 --and (@i < 2)
	BEGIN
		select top 1 @LinkRule = Link_Rule, @ExecStr = Exec_Proc, @CodeRow = CodeRow
		from #t_KS
		where algorithm = 9 and Val_Type = 2 AND Link_RULE > 0
       
	
	--select @ExecStr
		print @ExecStr
		insert #tmp 
		exec sp_executesql @ExecStr, N'@CodeRow varchar(100)', @CodeRow = @CodeRow

		insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
		select (select top 1 Value from #tmp), @LinkRule, 0, @CodeRow
		from #t_KS_Left L
		where Link_Rule = @LinkRule and ((Val_Type = 0 and Link_Col is NOT NULL and Link_Row is NOT NULL) or (Val_Type = 3 and Link_Col is NOT NULL and Code_Row <> ''))
            AND (SELECT COUNT(*) FROM #t_KS K WHERE K.Link_RULE = L.Link_Rule) < 2
             AND CodeRow = @CodeRow 


      UPDATE #t_ks
      SET VALUE = (select top 1 Value from #tmp)
      WHERE @LinkRule = Link_Rule and Val_Type = 2  AND CodeRow = @CodeRow AND [Exec_Proc] = @ExecStr

		delete #tmp
		update #t_KS SET Link_Rule = -Link_Rule where Link_Rule = @LinkRule AND CodeRow = @CodeRow  AND [Exec_Proc] = @ExecStr
		exec sp_executesql N'select @count = count(*) from #t_KS where algorithm  = 9 and Link_Rule > 0 and Val_Type = 2', 
					   N'@count int output', @count = @a_count OUTPUT
	end


	delete #t_KS
	where algorithm = 4

   UPDATE #t_KS
   SET Link_Rule = ABS(Link_RULE)
   
   DELETE #t_KS WHERE [algorithm] = 9 AND (SELECT COUNT(*) FROM #t_KS K WHERE K.Link_RULE = #t_KS.Link_Rule) < 2
   
 

	-------------------------------------------------------------------------------------------
	-- деление и умножение и т.д.
	update #t_KS
   SET VALUE = CASE K.Val_Type
                    WHEN 0 THEN CASE 
                                     WHEN K.[property]&2=0 THEN ISNULL(RS.Summa ,0)
                                         *px
                                     ELSE ISNULL(ABS(RS.Summa) ,0)*px
                                END
                    WHEN 1 THEN K.Factor*px
                    WHEN 3 THEN  CASE 
                                 WHEN K.[property]&2=0 THEN ISNULL(RD.Float_Val ,0)
                                     *px
                                 ELSE ISNULL(ABS(RD.Float_Val) ,0)*px END 
                    ELSE K.[Value]
               END
	from #t_KS K
		left join #t_summa RS on K.link_Col = RS.Link_Col and K.Link_Row = RS.Link_Row
		left join #report_dinamics RD on K.Link_Col = RD.Link_Col and RD.Code_Row = K.Code_Row

	insert @t_temp
	select *
	from #t_KS K
	where CodeRow = '' and exists(select top 1 * from #t_KS K2 where K.Link_Rule = K2.Link_Rule and CodeRow <> '')


	delete #t_KS
	from #t_KS K
	where CodeRow = '' and exists(select top 1 * from #t_KS K2 where K.Link_Rule = K2.Link_Rule and CodeRow <> '')

	-- и для вычисления нужно добавть операнды, которые не размножились
	insert #t_KS
	select K.Link_Rule, K.OrderRow, val_type, [sign], Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], S.orderCol, S.CodeRow, cOrderTable, cOrderCol, px_comment, [property]
	from @t_temp K left join (select distinct Link_Rule, orderCol, CodeRow from #t_KS) S on K.Link_Rule = S.Link_Rule 
	where not exists(select top 1 * from #t_KS S1 where S1.Link_Rule = K.Link_Rule and S1.OrderRow = K.OrderRow and S.CodeRow = S1.CodeRow)

	-- правая часть
	update #t_KS
	set OrderRow = OrderRow - OrRow + 1
	from #t_KS K, (select min(OrderRow) as OrRow, Link_Rule from #t_KS K1 where  part = 1 group by Link_Rule) K2
	where K.Link_Rule = K2.Link_Rule

	insert #t_Result_C ([Value], Link_Rule, orderCol, CodeRow)
	select case [sign] when '+' then Value else -Value end, Link_Rule, orderCol, CodeRow
	from #t_KS K
	where OrderRow = 1

	set @maxOrderRow = isnull((select max(orderRow) from #t_KS ),0)
	set @i = 2
	
	while @i<=@maxOrderRow
	begin

		update R
		set Value = case [sign] when '*' then R.Value * K.Value
								when '/' then case K.Value when 0 then 0 else R.Value / K.Value end
								when '+' then R.Value + K.Value
								when '-' then R.Value - K.Value
					end 
		from #t_Result_C R, #t_KS K
		where K.orderRow = @i and R.Link_Rule = K.Link_Rule and isnull(R.orderCol,0) = isnull(K.orderCol,0) and isnull(R.CodeRow, '') = isnull(K.CodeRow,'') 

		set @i = @i + 1
	end

	-- записываем результат

	update Res
	set Link_Col = K.Link_Col,
		Link_Table = K.Link_Table,
		Value =  round( Res.Value, C.Val_Len) 
	from #t_Result_C Res
         JOIN #t_KS_Left K ON Res.orderCol = 0 and K.Link_Rule = Res.Link_Rule 
         join #t_Col C on K.Link_Col = C.Link_Col

	update Res
	set Link_Col = C.Link_Col,
		Link_Table = K.Link_Table,
		Value = round(CAST(Res.Value AS NUMERIC(22,5)), C.Val_Len) 
	from     #t_KS_Left K 
            join #t_Col C on K.Link_Table = C.Link_Table
            join #t_Result_C Res ON K.Link_Rule = Res.Link_Rule and Res.orderCol = C.orderCol

	update Res
	set Value =  ABS(Res.Value) 
	from     #t_Rules R 
            join #t_Result_C Res ON R.Link_Rule = Res.Link_Rule AND  isnull(IsDoschet, 0) & 16 = 16 


	update #t_Result_C
	set Link_Row = K.Link_Row, CodeRow = R.Code
	from #t_KS_Left K  left join #t_Rows_Static R on K.Link_Row = R.Link_Row
	where isnull(#t_Result_C.CodeRow, '') = '' and K.Val_Type = 0 and K.Link_Rule = #t_Result_C.Link_Rule

	update #t_Result_C
	set Link_Row = R.Link_Row
	from #t_KS_Left K left join #t_Rows_Static R on K.Link_Table = R.Link_Table
	where isnull(#t_Result_C.CodeRow, '') <> '' and K.Val_Type = 0 and K.Link_Rule = #t_Result_C.Link_Rule and R.Code = #t_Result_C.CodeRow

	update #t_Result_C
	set CodeRow = K.Code_Row
	from #t_KS_Left K 
	where isnull(#t_Result_C.CodeRow, '') = '' and K.Val_Type = 3 and K.Link_Rule = #t_Result_C.Link_Rule --and K.orderCol = #t_Result_C.orderCol

	delete #t_Result_C where Link_Col is NULL or (Link_Row is NULL and isnull(CodeRow, '') = '') or Value is NULL
	
	update #report_dinamics
	set float_val = R.Value
	from #t_Result_C R
	where R.Link_Row is NULL and R.Link_Col = #report_dinamics.Link_Col
			and R.CodeRow = #report_dinamics.Code_Row

	insert #report_dinamics(Link_SF, Code_Row, link_col, float_val, str_val, Link_Table)
	select @LSF, R.CodeRow, R.Link_Col, max(R.Value), '', R.Link_Table
	from #t_Result_C R 
	where R.Link_Row is NULL and not exists(select top 1 * from #report_dinamics S where S.Link_Col = R.Link_Col and R.CodeRow = S.Code_Row)
	group by 	R.CodeRow, R.Link_Col, R.Link_Table

	update #t_summa
	set Summa = R.Value
	from #t_Result_C R
	where R.Link_Col = #t_summa.Link_Col and R.Link_Row = #t_summa.Link_Row and R.Link_Row is NOT NULL
	insert #t_summa(LSF, link_col, link_row, Code, summa)
	select @LSF, R.Link_Col, R.Link_Row, max(R.CodeRow), max(R.Value)
	from #t_Result_C R 
	where R.Link_Row is NOT NULL and not exists(select top 1 * from #t_summa S where S.Link_Col = R.Link_Col and S.Link_Row = R.Link_Row)
	group by R.Link_Col, R.Link_Row

	delete @t_temp
	truncate table #t_KS_Left
	truncate table #t_KS
	truncate table #t_Result_C	
end
if @MaxCalcOrders < 100
	exec dbo.RO_Tree_KBK_doschet @LSF
   
   
   
-------------------------------------------------------------------------------
if @cProgressTable <>'' begin
  set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Обновление данных'', percents = 80'
         exec sp_executesql @strProgressExec
 end

update report_summa
set summa = RS.summa
from #t_summa RS join #t_Col on RS.Link_Col = #t_Col.Link_Col
where Link_saved_form = @LSF and RS.Link_Col = report_summa.Link_Col and RS.Link_Row = report_summa.Link_Row

insert report_summa (Link_Saved_form, Link_Col, Link_Row, Summa)
select @LSF, RS.Link_Col, Link_Row, max(Summa)
from #t_summa RS join #t_Col on RS.Link_Col = #t_Col.Link_Col
where not exists(select top 1 * from report_summa RS1 where link_saved_form = @LSF and RS1.Link_Col = RS.Link_Col and RS.Link_Row = RS1.Link_Row)
group by RS.Link_Col, Link_Row
/*
update report_dinamics
set float_val = RD.float_val,
	str_val = RD.str_val
	from report_dinamics D inner join #report_dinamics RD on D.Link_SF = @LSF and RD.Link_Col = D.Link_Col and RD.Code_Row = D.Code_Row
*/

update report_dinamics
set float_val = RD.float_val
from #report_dinamics RD join #t_Col on RD.Link_Col = #t_Col.Link_Col
where report_dinamics.Link_SF = @LSF and RD.Link_Col = report_dinamics.Link_Col and RD.Code_Row = report_dinamics.Code_Row and RD.Float_Val <> report_dinamics.Float_Val


--delete #report_dinamics
--where exists(select top 1 * from report_dinamics RD (NOLOCK) where Link_SF = @LSF and RD.Link_Col = #report_dinamics.Link_Col and RD.Code_Row = #report_dinamics.Code_Row)

delete #report_dinamics
where (isnull(Float_Val,0) = 0 and isnull(Str_Val,'') = '')


----------------------------------------------------------------------------------------------------------
-- колонки, которые можно загрузить из справочника, для динамических таблиц
if @cProgressTable <>'' begin
  set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Загрузка данных из справочника'', percents = 85'
         exec sp_executesql @strProgressExec
 end

declare @table table (orders tinyint)
IF @cTables=''
BEGIN
        insert @table (orders)
        select orders from #report_tables where Val_Type = 1
END
ELSE
BEGIN
        insert @table (orders)
        select orders from #report_tables RT where RT.Val_Type = 1
        and exists(select * from #iTables IT where IT.link_Table=RT.Link_table)
END

while Exists(select * from @table)
begin
  select @orderTable=orders from @table  
  exec dbo.RN_FILL_WITH_DICT @LSF,@LinkF, @orderTable, @cTMP_Table = '#', @varKSiNotUpdate = 1
  delete @table where orders=@orderTable  
end
-------------------------------------------------------------------------------
if @cProgressTable <>'' begin
  set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Добавление данных'', percents = 95'
         exec sp_executesql @strProgressExec
 end

insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
select distinct @LSF, RD.Link_Col, Code_Row, isnull(Float_Val,0), ''
from #report_dinamics RD join #t_Col on RD.Link_Col = #t_Col.Link_Col
where not exists(select top 1 * from report_dinamics RD1 where RD1.Link_SF = @LSF and RD1.Link_Col = RD.Link_Col and RD1.Code_Row = RD.Code_Row)
	and isnull(Str_Val,0) = ''

insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
select distinct @LSF, RD.Link_Col, Code_Row, isnull(Float_Val,0), isnull(Str_Val,'')
from #report_dinamics RD 
where not exists(select top 1 * from report_dinamics RD1 where RD1.Link_SF = @LSF and RD1.Link_Col = RD.Link_Col and RD1.Code_Row = RD.Code_Row)
	and isnull(Str_Val,0) <> ''

--group by Link_Col, Code_Row

-----------------------------------------------------------------------------------------------------------
if @cProgressTable <>'' begin
  set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Завершение расчета итогов'', percents = 95'
         exec sp_executesql @strProgressExec
 end

    exec dbo.RN_SPLIT_CODE_ROW @LSF

drop table #report_coloumns
drop table #t_Col
drop table #t_KS
drop table #t_Row_KS
drop table #t_Rules
drop table #t_Result_C
drop table #t_Rows_Static
drop table #tmp
drop table #report_dinamics
drop table #t_Summa
drop table #report_tables
drop table #t_KS_Left
drop table #t_Rules_region

--GO
--GRANT ALL ON dbo.[RO_CALCULATE_INSIDE1] TO PUBLIC



GO
GRANT ALL ON dbo.[RO_CALCULATE_INSIDE] TO PUBLIC

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[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),
		@iKbkLen int
---------------
				
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

if Year(@dCALC_DATE) < 2016
	set @iKbkLen = 17
else
	set @iKbkLen = 20

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), -- Признак платежа000
	[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) + '00000000000000000000',@iKbkLen) + 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,@iKbkLen - 10), -- ЦСР
	[COL9] = substring(rtrim(KBK),@iKbkLen - 2,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) + '00000000000000000000',@iKbkLen) + 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.[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.[BB_GET_LINK_KBK_BY_CODE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BB_GET_LINK_KBK_BY_CODE]

GO




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

CREATE      PROCEDURE dbo.BB_GET_LINK_KBK_BY_CODE
	@iLinkKBK	 int=0 output,
	@iLinkEKR	 int=0 output,
	@cErrorTxt 	 varchar(100) output,
	@cCodeKBK 	 varchar(30) = '',
	@cTypeKBK 	 varchar(2) = '',
	@addVKR		 tinyint = 1 -- Добавить отсутсвущие ВКР
	
AS
declare @varKSiRet int,
	@iL_PPP	   int,
	@iL_Razd   int,
	@iL_C_St   int,
	@iL_Rash   int,
	@iLinkIVF  int,
	@iLinkD    int,

	@varKSCode_PPP	 char(3),
	@varKSCode_Razd	 char(4),
	@varKSCode_CelSt char(7),
	@varKSCode_Rash	 char(3),
	@varKSCode_Ekr	 char(3),
	@cCodeIVF		 char(14),
	@cCodeD			 char(14),
	@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,'.','') = left(@cCodeKBK,17)
	if @iLinkKBK is null
		set @cErrorTxt = 'Не найден КБК в справочнике'

end
-- ВКР
IF @cTypeKBK = '10'
begin
select @varKSCode_PPP = left(@cCodeKBK,3),
		@varKSCode_Razd = substring(@cCodeKBK,4,4),
		@varKSCode_CelSt = substring(@cCodeKBK,8,7),
		@varKSCode_Rash = substring(@cCodeKBK,15,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 = 'Запрещено добавление КБК в справочник.'

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,14)
	
	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
			
			SET @iLinkKBK = 0
			exec @varKSiRet = dbo.BI_SAVE_KBK @iLinkKBK output, @iTypeKBK, 'Сгенерированный ИВФ', @iL_PPP, null, @iLinkIVF, null, null, null, null
			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,14)
	
	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

			SET @iLinkKBK = 0
			exec @varKSiRet = dbo.BI_SAVE_KBK @iLinkKBK output, 2, 'Сгенерированный КД', @iL_PPP, @iLinkD, null, null, null, null, null
			
			if @varKSiRet <> 0 
				SET @varKSiRet = -1
		END
		ELSE
			set @cErrorTxt = 'Запрещено добавление КБК в справочник.'

end
if @cErrorTxt <> '' 
	SET @varKSiRet = -1

IF (select count(link) from dictionary_item where code = @varKSCode_Ekr) = 1
	select @iLinkEKR = link from dictionary_item where code = @varKSCode_Ekr
ELSE
	set @varKSiRet = -2 



return @varKSiRet





GO


GRANT EXECUTE ON dbo.[BB_GET_LINK_KBK_BY_CODE] 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.[SALARY_FILL_DED_ESN_VKR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SALARY_FILL_DED_ESN_VKR]

GO

CREATE PROCEDURE [dbo].SALARY_FILL_DED_ESN_VKR
--Начисление страховых взносов
@RefPay int, 
@LinkVKR int,
@LINK_EKR INT, 
@linkPers int, 
@Month int, 
@Year int, 
@FlagMS  tinyint,
@FlagShow int = 0,
@DEP_LINK INT  = NULL,
@LinkVKR2 INT = NULL 
AS

SET NOCOUNT ON

IF @LinkVKR2 IS NULL
	SET @LinkVKR2 = @LinkVKR

DECLARE 
	@DATE1 datetime, 
	@linkFace int,
	@LINK_213EKR INT,
	@LINK_211EKR INT,
	@TARIF TINYINT,
	@SHOW_212 TINYINT,
	@LINK_EKR_ADD INT
		  
SET @TARIF = ISNULL((SELECT TOP 1 ENVD FROM dbo.SAL_SFIN WHERE LINK = @LinkVKR),0) + 1	
		  
SET @LINK_211EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '211')
SET @LINK_EKR_ADD = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '212')
SET @LINK_213EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')
SET @FlagMS = 1
SET @SHOW_212 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_3')

IF @SHOW_212 = 1 OR @LINK_EKR <> @LINK_211EKR
	SET @LINK_EKR_ADD = @LINK_EKR
	
DECLARE @ESN_OPTIONS_7 INT --Начислять доп. тариф только для полной ставки
--При включенной опции программа будет начислять страховые взносы по доп. тарифам только если у сотрудника по основной должности полная ставка. 
--Если ставка не полная, то доп. тариф не начисляется.
SET @ESN_OPTIONS_7 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_7')

DECLARE @ESN_OPTIONS_8 INT --Начислять доп. тариф внутренним совместителям
--При включенной опции программа будет начислять страховые взносы по доп. тарифам на доходы внутренних совместителей.
SET @ESN_OPTIONS_8 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_8')

DECLARE @DATE_BEG DATETIME
SET @DATE_BEG = dbo.convertDMY2Date(1,@Month,@Year)
SET @DATE1 = dbo.DateEndOfMonth(@DATE_BEG)

DECLARE @DATE_YEAR_BEG DATETIME
SET @DATE_YEAR_BEG = dbo.convertDMY2Date(1,1,@Year)

SELECT @linkFace = @linkPers 

DECLARE @T1 TABLE
([NUM]			[int],
 [SUMMA]		[numeric](19,2),
 [SUMMA_VKR]		[numeric](19,2),
 [SUMMA_M]		[numeric](19,2),
 [SUMMA_M_VKR]		[numeric](19,2))


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

declare @linkEmpl int,  @Pred_Mesto_Rab numeric(15,2), 	  @FlagD int

SET @linkEmpl = 
	(SELECT TOP 1 IM.EMPL_LINK
	FROM
		DBO.EMPL E with (nolock)
		LEFT JOIN DBO.ITEM_MOVE IM with (nolock) ON IM.EMPL_LINK = E.LINK AND IM.ACTIVE = 1 AND IM.NEW_FACE=1 AND IM.[STATUS] IN (1,3) AND IM.DATE_BEGIN <= @DATE1
		LEFT JOIN DBO.ITEM_DIS_FACE IDF with (nolock) ON IDF.EMPL_LINK = E.LINK AND IDF.ACTIVE=1 AND COALESCE(IDF.DIS_DATE,'20990101') >= dbo.DateBeginOfMonth(@DATE1)
	WHERE
		E.DEP_LINK = @DEP_LINK
		AND
		E.PERS_LINK = @linkPers
	ORDER BY
		DATE_BEGIN DESC	
	)	

---------------------------------------------------
DECLARE @item_move TABLE (LINK INT, EMPL_LINK INT, STAFF_LINK INT, DATE_BEGIN DATETIME, DATE_END DATETIME, NUM_STAKE NUMERIC(5,3), active TINYINT, NEW_FACE TINYINT, [STATUS] TINYINT)
INSERT INTO @item_move (LINK, EMPL_LINK, STAFF_LINK, DATE_BEGIN, DATE_END, NUM_STAKE, active, NEW_FACE, [STATUS])
Select 
	P1.LINK, P1.EMPL_LINK, P1.STAFF_LINK, P1.DATE_BEGIN, P1.DATE_END, P1.NUM_STAKE, P1.active, P1.NEW_FACE, P1.[STATUS]
from 
	dbo.empl e INNER JOIN dbo.item_move P1 ON P1.EMPL_LINK = e.link
WHERE
	E.DEP_LINK = @DEP_LINK AND E.PERS_LINK	= @linkPers
---------------------------------------------------

--Информация о размере ставок по каждому табельному номеру
DECLARE @NUM_STAKE TABLE (LINK_EMPL INT, NUM_STAKE NUMERIC(18,4), DATE_BEG DATETIME, DATE_END DATETIME)
INSERT INTO @NUM_STAKE (LINK_EMPL, NUM_STAKE, DATE_BEG, DATE_END)
SELECT DISTINCT
	EMPL_LINK, NUM_STAKE, DATE_BEGIN, DATE_END 
FROM @item_move
WHERE active = 1 AND NEW_FACE <> 3 AND @DATE1 BETWEEN DATE_BEGIN AND DATE_END

if @FlagShow = 1 
	select 'Сотрудник:  '+ LTRIM(RTRIM(P.FM)) + ' ' + SUBSTRING(LTRIM(RTRIM(P.IM)),1,1) + '.' + SUBSTRING(LTRIM(RTRIM(P.OT)),1,1)
		+  ', месяц ' + convert(varchar(2),@Month)+ ', год ' +convert(varchar(4),@Year) as [Исходные данные],
		[Отчисление] = (select rtrim(name) from pays where link =@RefPay)  FROM dbo.PERSON P where link = @linkFace


DECLARE @NASTR TABLE
([LINK_MINROT] 	[int],
 [REF_PAY]			[int],
 [CODE]				[varchar](5),
 [NAME]				[varchar](254),
 [PREDEL]			[numeric](19, 2))

INSERT INTO @NASTR([LINK_MINROT],[REF_PAY],[CODE],[NAME],[PREDEL])
SELECT [LINK_MINROT],[REF_PAY],[CODE],[NAME],[PREDEL] FROM dbo.Salary_deduct_esn(@DATE1)

SELECT @Pred_Mesto_Rab = 0, @FlagD = 0

IF dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_6 ') = 1
BEGIN
	IF YEAR(dbo.kd_DateBeginWork(@linkEmpl,null)) = @Year
	BEGIN
		SET @Pred_Mesto_Rab = (SELECT ISNULL(SUM(SUMMA_DED),0) FROM dbo.SD_EMPL_PREV_DED WHERE LINK_EMPL = @linkEmpl and LINK_DED in (select REF_PAY from @NASTR))
		IF @Pred_Mesto_Rab IS null or @Pred_Mesto_Rab < 0
			SET @Pred_Mesto_Rab = 0
		SET @FlagD = 1
		
		IF  @FlagShow = 1 
			SELECT 'Совокупный доход: '+ rtrim(isnull(convert(varchar(100),(select sum(summa_TYP_INCOMS) from dbo.SD_EMPL_PREV_DOHOD where link_empl =@linkEmpl)),'0')) + ' , вычеты: '+
			 rtrim( isnull( convert(varchar(100),(select sum(summa_ded) from dbo.SD_EMPL_PREV_DED where link_empl =@linkEmpl and LINK_DED in (select REF_PAY from @NASTR) )),'0'))  as 'Данные с предыдущего места работы'
	END
END	

---Учитываются доходы по договорам ГПХ в данной организации, чтобы правильно применить регрессионную шкалу---
DECLARE @SUM_DGH numeric(15,2)
SET @SUM_DGH = 
	ISNULL(
	(
	SELECT SUM(GT.SUMMA_BASE)
	FROM dbo.DOCUMENTS_DGH G INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	WHERE FLAG_JC = 1
			AND YEAR(G.[DATE]) = @Year
			AND MONTH(G.[DATE]) <= @Month
			AND G.LINK_DEP = @DEP_LINK
			AND GT.LINK_PAY = @RefPay
			AND GT.PERS_LINK = @linkFace
	),0)

IF @SUM_DGH <> 0 AND @FlagShow = 1 
	SELECT 'Совокупный доход: '+ rtrim(isnull(convert(varchar(100),@SUM_DGH),'0')) as 'Доход по договорам ГПХ'


CREATE TABLE #PERIODY (LINK_EMPL INT, LINK_PERSON INT, TAB VARCHAR(10), NUM_STAKE NUMERIC(18,4), POSTNAME VARCHAR(50), st_date1 datetime, st_date2 datetime, im_date1 datetime, im_date2 datetime, [COD_SPO_USL_TRUD] int)

---------------------------------------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC IN (10,11) AND LINK = @RefPay)
BEGIN

	--sa_item_move
	--	
	DECLARE @sa_item_move TABLE (EMPL_LINK INT, STAFF_LINK INT, DATE_BEGIN DATETIME, DATE_END3 DATETIME, NUM_STAKE NUMERIC(5,3), [STATUS] TINYINT )

	INSERT INTO @sa_item_move (EMPL_LINK, STAFF_LINK, DATE_BEGIN, DATE_END3, NUM_STAKE, [STATUS])
	Select 
		P1.EMPL_LINK, P1.STAFF_LINK, P1.DATE_BEGIN, date_end3 = min(P2.date_begin) - 1, P1.NUM_STAKE, P1.[STATUS]
	from 
		dbo.empl e
		INNER JOIN @item_move P1 ON P1.EMPL_LINK = e.link
		INNER JOIN @item_move P2 on P1.EMPL_LINK = P2.EMPL_LINK
	where
		E.PERS_LINK	= @linkPers 
		AND P1.active = 1 AND P2.active = 1 AND P1.NEW_FACE <> 3 AND P2.NEW_FACE <> 3
		AND P1.[date_begin] < P2.[date_begin] 
	group by 
		P1.EMPL_LINK, P1.STAFF_LINK, P1.DATE_BEGIN, P1.NUM_STAKE, P1.[STATUS]

	INSERT INTO @sa_item_move (EMPL_LINK, STAFF_LINK, DATE_BEGIN, DATE_END3, NUM_STAKE, [STATUS])
	Select 
		P3.EMPL_LINK, P3.STAFF_LINK, P3.DATE_BEGIN, date_end3 = '99991231', P3.NUM_STAKE, P3.[STATUS]
	from
		dbo.empl e 
		INNER JOIN @item_move P3 ON P3.EMPL_LINK = e.link
	where
		E.PERS_LINK	= @linkPers  
		AND
		P3.active = 1 AND P3.NEW_FACE <> 3
		AND
		NOT EXISTS (
					Select *
					from 
						@item_move P1 inner join @item_move P2 on P1.EMPL_LINK = P2.EMPL_LINK
					where
						P1.LINK = P3.link
						AND P1.active = 1 and P2.active = 1 AND P1.NEW_FACE <> 3 AND P2.NEW_FACE <> 3
						and P1.[date_begin] < P2.[date_begin] 
					)
	-----------------------------------------------------------------------------------------------------

	CREATE TABLE #ADD_TYPE (
		[type] INT IDENTITY(1,1),
		[TERR_USL_TRUD] int NULL ,
		[TERR_RK] numeric(3, 2) NULL ,
		[OSOB_USL_TRUD] int NULL ,
		[COD_POS_SPISOK] int NULL ,
		[COD_POS_SPISOK2] int NULL ,
		[USL_DOSROCH_PENS] int NULL ,
		[STAVKA_PED_MED] numeric(3, 2) NULL,
		[COD_SPO_USL_TRUD] int NULL
	)

	INSERT INTO #ADD_TYPE 
	SELECT DISTINCT ISNULL(TERR_USL_TRUD,0), ISNULL(TERR_RK,0), ISNULL(OSOB_USL_TRUD,0), ISNULL(COD_POS_SPISOK,0), ISNULL(COD_POS_SPISOK2,0), ISNULL(USL_DOSROCH_PENS,0), ISNULL(STAVKA_PED_MED,0), ISNULL([COD_SPO_USL_TRUD],0)
	FROM dbo.staff
	WHERE ISNULL(COD_POS_SPISOK,0) <> 0 OR ISNULL(COD_POS_SPISOK2,0) <> 0

	INSERT INTO 
		#PERIODY (LINK_EMPL, LINK_PERSON, TAB, NUM_STAKE, POSTNAME, st_date1, st_date2, im_date1, im_date2, [COD_SPO_USL_TRUD])
	SELECT DISTINCT
		E.LINK,
		E.PERS_LINK,
		TAB,
		IM.NUM_STAKE,
		LEFT(PT.NAME,50),
		st_date1 = dbo.DateBeginOfMonth((case when st.DATE_BEGIN >= @DATE_YEAR_BEG then st.DATE_BEGIN else @DATE_YEAR_BEG end)),
		st_date2 = dbo.DateEndOfMonth((case when coalesce(st.DATE_END,@DATE1) <= @DATE1 then coalesce(st.DATE_END,@DATE1) else @DATE1 end)	),
		im_date1 = dbo.DateBeginOfMonth((case when im.DATE_BEGIN >= @DATE_YEAR_BEG then im.DATE_BEGIN else @DATE_YEAR_BEG end)),
		im_date2 = dbo.DateEndOfMonth( 
							CASE WHEN COALESCE(U.DIS_DATE,'20990101') <= (case when ISNULL(ISNULL(U.DIS_DATE,im.DATE_END3),@DATE1) <= @DATE1 then ISNULL(ISNULL(U.DIS_DATE,im.DATE_END3),@DATE1) else @DATE1 end)
								THEN COALESCE(U.DIS_DATE,'20990101')
								ELSE (case when ISNULL(ISNULL(U.DIS_DATE,im.DATE_END3),@DATE1) <= @DATE1 then ISNULL(ISNULL(U.DIS_DATE,im.DATE_END3),@DATE1) else @DATE1 end)
							END	),
		T.[COD_SPO_USL_TRUD]							
	FROM 
		dbo.empl e
		INNER JOIN @sa_item_move im ON im.EMPL_LINK = e.link
		inner join dbo.staff_head sh on sh.link = STAFF_LINK
		inner join dbo.staff st on st.link_up = sh.link
		INNER JOIN dbo.POST PT ON PT.LINK = st.post_link
		INNER join #ADD_TYPE T on ISNULL(st.TERR_USL_TRUD,0) = ISNULL(T.TERR_USL_TRUD,0) 
								AND ISNULL(st.TERR_RK,0) = ISNULL(T.TERR_RK,0) 
								AND ISNULL(st.OSOB_USL_TRUD,0) = ISNULL(T.OSOB_USL_TRUD,0) 
								AND ISNULL(st.COD_POS_SPISOK,0) = ISNULL(T.COD_POS_SPISOK,0) 
								AND ISNULL(st.COD_POS_SPISOK2,0) = ISNULL(T.COD_POS_SPISOK2,0) 
								AND ISNULL(st.USL_DOSROCH_PENS,0) = ISNULL(T.USL_DOSROCH_PENS,0) 
								AND ISNULL(st.STAVKA_PED_MED,0) = ISNULL(T.STAVKA_PED_MED,0)
								AND ISNULL(st.COD_SPO_USL_TRUD,0) = ISNULL(T.COD_SPO_USL_TRUD,0)
		LEFT JOIN dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1	
	where
		E.PERS_LINK	= @linkPers
		and  
		im.DATE_BEGIN <= @DATE1 and im.DATE_END3 >= @DATE_YEAR_BEG
		AND
		IM.[STATUS] <> 2 --Вредность у внутренних совместителей не учитываем (НЕ ДОЛЖНО БЫТЬ)
		AND
		st.DATE_BEGIN <= @DATE1 and st.DATE_END >= @DATE_YEAR_BEG
		AND
		T.[TYPE] IS NOT NULL
		AND
		(
			ISNULL(T.[COD_POS_SPISOK],0) <> 0 AND EXISTS (SELECT * FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 AND LINK = @RefPay)
			OR
			ISNULL(T.[COD_POS_SPISOK2],0) <> 0 AND EXISTS (SELECT * FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 AND LINK = @RefPay)	
		)	

	if @FlagShow = 1 
		SELECT DISTINCT TAB AS [Таб_номер],  LEFT(dbo.ku_GetEmplSubdivName(LINK_EMPL,@DATE1),50) AS [Отдел], POSTNAME AS [Должность], CONVERT(VARCHAR(10), ST_DATE1, 104) AS 'Нач_пер_с_вредн_ШР', CONVERT(VARCHAR(10),ST_DATE2,104) AS 'Оконч_пер_с_вредн_ШР' FROM #PERIODY
			
	if @FlagShow = 1 
		SELECT DISTINCT TAB AS [Таб_номер],  NUM_STAKE AS [Кол-во ставок], LEFT(dbo.ku_GetEmplSubdivName(LINK_EMPL,@DATE1),50) AS [Отдел], POSTNAME AS [Должность], CONVERT(VARCHAR(10), IM_DATE1, 104) AS 'Нач_пер_с_вредн_должность', CONVERT(VARCHAR(10),IM_DATE2,104) AS 'Оконч_пер_с_вредн_должность', CASE WHEN NUM_STAKE < 1 THEN 'Доп. тариф не начисляется, т.к. не полный день' ELSE '' END AS [Примечание]
		FROM #PERIODY
	
	INSERT INTO @T1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
	SELECT M.NUM,SUM(SJ.SUMMA) AS SUMMA, 			
			 [SUMMA_VKR]	= SUM(CASE WHEN SJ.LINK_VKR = @LinkVKR2 AND SJ.LINK_EKR IN (@LINK_EKR,@LINK_EKR_ADD) THEN SJ.SUMMA ELSE 0 END),
			 [SUMMA_M] 		= SUM(CASE WHEN MONTH(SJ.PERIOD_BEGIN) = M.NUM THEN SJ.SUMMA ELSE 0 END),
			 [SUMMA_M_VKR] = SUM(CASE WHEN (MONTH(SJ.PERIOD_BEGIN) = M.NUM) AND (SJ.LINK_VKR = @LinkVKR2 AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) THEN SJ.SUMMA ELSE 0 END)
	FROM 
		dbo.MONTHS M
		INNER JOIN dbo.EMPL E ON 1=1
		INNER JOIN dbo.CALCULATE_JURNAL SJ ON SJ.LINK_EMPL = E.LINK
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
	WHERE 
		E.PERS_LINK = @linkFace
		AND (M.NUM <= @Month) 
		AND (MONTH(SJ.PERIOD_BEGIN) <= M.NUM) 
		AND (YEAR(SJ.PERIOD_BEGIN) = @Year)
		AND TR.LINK_TAX = @RefPay 
		AND EXISTS (SELECT * FROM #PERIODY P WHERE 
												(@ESN_OPTIONS_7 = 0 OR @ESN_OPTIONS_7 = 1 AND P.NUM_STAKE >=1)
												AND 
												(
													@ESN_OPTIONS_8 = 0 AND P.LINK_EMPL = SJ.LINK_EMPL 
													OR
													@ESN_OPTIONS_8 = 1 AND P.LINK_PERSON = E.PERS_LINK
												)	
												AND SJ.PERIOD_BEGIN <= P.ST_DATE2 
												AND SJ.PERIOD_END >= P.ST_DATE1 
												AND SJ.PERIOD_BEGIN <= P.IM_DATE2 
												AND SJ.PERIOD_END >= P.IM_DATE1)
	GROUP BY  M.NUM	

	
END
---------------------------------------------------------------------------------------------------------------
ELSE
	INSERT INTO @T1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
	SELECT M.NUM,SUM(SJ.SUMMA) AS SUMMA, 			
			 [SUMMA_VKR]	= SUM(CASE WHEN SJ.LINK_VKR = @LinkVKR2 AND SJ.LINK_EKR IN (@LINK_EKR,@LINK_EKR_ADD) THEN SJ.SUMMA ELSE 0 END),
			 [SUMMA_M] 		= SUM(CASE WHEN MONTH(SJ.PERIOD_BEGIN) = M.NUM THEN SJ.SUMMA ELSE 0 END),
			 [SUMMA_M_VKR] = SUM(CASE WHEN (MONTH(SJ.PERIOD_BEGIN) = M.NUM) AND (SJ.LINK_VKR = @LinkVKR2 AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) THEN SJ.SUMMA ELSE 0 END)
	FROM 
		dbo.MONTHS M
		INNER JOIN dbo.CALCULATE_JURNAL SJ ON 1=1 
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
		INNER JOIN dbo.EMPL E ON SJ.LINK_EMPL = E.LINK
	WHERE 
		(TR.LINK_TAX = @RefPay) 
		AND (E.PERS_LINK = @linkFace) 
		AND (MONTH(SJ.PERIOD_BEGIN) <= M.NUM) AND (M.NUM <= @Month) AND (YEAR(SJ.PERIOD_BEGIN)=@Year)
		AND sj.LINK_DEP = @DEP_LINK
	GROUP BY  M.NUM


if @FlagShow = 1 
	SELECT [num] as [Месяц], [summa] as [Сумма с нач года],summa_vkr as [Сумма с нач года по ВКР/ЕКР], summa_m as [Сумма за месяц], 
	summa_m_vkr as [Сумма за месяц по ВКР/ЕКР]  FROM @T1

--Если суммы, которые раньше были в базе убрали из базы, теперь базовой суммы вообще нет
IF NOT EXISTS(SELECT * FROM @T1)
	INSERT INTO @T1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
	VALUES(@Month, 0, 0, 0, 0)

DECLARE @Temp1_1 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [MP]				[numeric](19,2),
 [MP_M]			[numeric](19,2),
 [MP_M_VKR]		[numeric](19,2))

--------------------------------------------------
CREATE TABLE #DICTIONARY_TYP_INCOMS (LINK INT)
INSERT INTO #DICTIONARY_TYP_INCOMS (LINK)
SELECT LINK FROM dbo.DICTIONARY_TYP_INCOMS WHERE EXISTS (SELECT * FROM @NASTR WHERE REF_PAY = REF_DEDUCT)
CREATE INDEX #DICTIONARY_TYP_INCOMS_IDX1 ON #DICTIONARY_TYP_INCOMS (LINK)

-------------------------------------------------
CREATE TABLE #PAYS (LINK INT)
INSERT INTO #PAYS (LINK)
SELECT P.LINK FROM dbo.PAYS P INNER JOIN #DICTIONARY_TYP_INCOMS I ON I.LINK = P.LINK_INC
CREATE INDEX #PAYS_IDX1 ON #PAYS (LINK)


--------------------------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC IN (10,11) AND LINK = @RefPay)
	
	INSERT INTO @Temp1_1 ([NUM],[LINK_PAYS],[MP],[MP_M],[MP_M_VKR])
	SELECT M.NUM,
			 [LINK_PAYS]= (SELECT LINK_INC  from pays where link = sj.LINK_PAYS),
			 [MP] 		= SUM(CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end), 
			 [MP_M] 		= SUM(CASE WHEN month(SJ.PERIOD_BEGIN)=m.num then (CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end) else 0 end),
			 [MP_M_VKR] = SUM(CASE WHEN ( month(SJ.PERIOD_BEGIN)=m.num)AND(sj.link_vkr = @LinkVKR2 AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) 
								THEN (CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end) else 0 end)
	FROM 
		dbo.MONTHS M 
		INNER JOIN dbo.S_J_C_Short SJ ON 1=1
		INNER JOIN #PAYS P ON P.LINK = SJ.LINK_PAYS
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
	WHERE 
		TR.LINK_TAX = @RefPay 
		AND (SJ.LINK_FACE = @linkFace)
		AND YEAR(SJ.PERIOD_BEGIN)=@Year AND M.NUM <= @Month 
		AND sj.LINK_DEP = @DEP_LINK
		AND EXISTS (SELECT * FROM #PERIODY P WHERE 
									(
										@ESN_OPTIONS_8 = 0 AND P.LINK_EMPL = SJ.LINK_EMPL
										OR
										@ESN_OPTIONS_8 = 1 AND P.LINK_PERSON = SJ.LINK_FACE
									)									
									AND SJ.PERIOD_BEGIN <= P.ST_DATE2 AND SJ.PERIOD_END >= P.ST_DATE1)		
		AND EXISTS (SELECT * FROM #PERIODY P WHERE 
									(
										@ESN_OPTIONS_8 = 0 AND P.LINK_EMPL = SJ.LINK_EMPL
										OR
										@ESN_OPTIONS_8 = 1 AND P.LINK_PERSON = SJ.LINK_FACE
									)	
									AND (@ESN_OPTIONS_7 = 0 OR @ESN_OPTIONS_7 = 1 AND P.NUM_STAKE >=1)
									AND SJ.PERIOD_BEGIN <= P.IM_DATE2 AND SJ.PERIOD_END >= P.IM_DATE1)		
	GROUP BY 
		M.NUM,SJ.LINK_PAYS
ELSE
	INSERT INTO @Temp1_1 ([NUM],[LINK_PAYS],[MP],[MP_M],[MP_M_VKR])
	SELECT M.NUM,
			 [LINK_PAYS]= (SELECT LINK_INC  from pays where link = sj.LINK_PAYS),
			 [MP] 		= SUM(CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end), 
			 [MP_M] 		= SUM(CASE WHEN month(SJ.PERIOD_BEGIN)=m.num then (CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end) else 0 end),
			 [MP_M_VKR] = SUM(CASE WHEN ( month(SJ.PERIOD_BEGIN)=m.num)AND(sj.link_vkr = @LinkVKR2 AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) 
								THEN (CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end) else 0 end)
	FROM 
		dbo.MONTHS M 
		INNER JOIN dbo.S_J_C_Short SJ ON 1=1
		INNER JOIN #PAYS P ON P.LINK = SJ.LINK_PAYS
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
	WHERE 
		TR.LINK_TAX = @RefPay 
		AND (SJ.LINK_FACE = @linkFace)
		AND YEAR(SJ.PERIOD_BEGIN)=@Year AND M.NUM <= @Month 
		AND sj.LINK_DEP = @DEP_LINK
	GROUP BY 
		M.NUM,SJ.LINK_PAYS
	

/*if @FlagShow = 1  
	select *  from @Temp1_1*/

DECLARE @Temp1 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [PREDEL]		[numeric](19,2),
 [MP]				[numeric](19,2),
 [MP_M]			[numeric](19,2),
 [MP_M_VKR]		[numeric](19,2))

INSERT INTO @Temp1 ([NUM],[LINK_PAYS],[PREDEL],[MP],[MP_M],[MP_M_VKR])
SELECT NUM,LINK_PAYS,
		[PREDEL] =  ISNULL((SELECT TOP 1 PREDEL FROM @NASTR 
								WHERE REF_PAY = (SELECT TOP 1 REF_DEDUCT FROM dbo.DICTIONARY_TYP_INCOMS WHERE LINK = LINK_PAYS)),0),
		SUM(MP) AS MP,
		SUM(MP_M) AS MP_M, 
		SUM(MP_M_VKR) AS MP_M_VKR
FROM @Temp1_1
GROUP BY NUM,LINK_PAYS

DECLARE @Temp2 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [PREDEL]		[numeric](19,2),
 [MP]				[numeric](19,2),
 [MP_M]			[numeric](19,2),
 [MP_M_VKR]		[numeric](19,2),
 [SALDO]			[numeric](19,2),
 [KOEF]			[numeric](19,10))

---


INSERT INTO @Temp2 ([NUM],[LINK_PAYS],[PREDEL],[MP],[MP_M],[MP_M_VKR],[SALDO],[KOEF]) 
SELECT T1.[NUM],T1.[LINK_PAYS],T1.[PREDEL],T1.[MP],T1.[MP_M],T1.[MP_M_VKR],
		 [SALDO] = (CASE WHEN @Pred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @Temp1 T2 WHERE T2.NUM <= T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0) > PREDEL
				THEN PREDEL
				ELSE @Pred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @Temp1 T2 WHERE T2.NUM <= T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0)
				END)
				- (CASE WHEN @Pred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @Temp1 T2 WHERE T2.NUM < T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0) > PREDEL
				THEN PREDEL
				ELSE @Pred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @Temp1 T2 WHERE T2.NUM < T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0)
				END),
		 [KOEF] 	= (CASE WHEN (SELECT SUM(MP_M) FROM @Temp1 T3 WHERE T3.NUM = T1.NUM AND T3.LINK_PAYS = T1.LINK_PAYS) = 0 
						THEN 0 ELSE (CASE WHEN (SELECT SUM(MP_M) 
				                         FROM @Temp1 T3 WHERE T3.NUM = T1.NUM AND T3.LINK_PAYS = T1.LINK_PAYS)= 0 
										  THEN 0 ELSE 										
											MP_M_VKR/(SELECT SUM(MP_M) 
                    				     FROM @Temp1 T3 WHERE T3.NUM = T1.NUM AND T3.LINK_PAYS = T1.LINK_PAYS) END) END)
FROM @Temp1 T1

declare @predel numeric(18,2)
Set @predel = COALESCE((SELECT TOP 1 PREDEL FROM @Temp1),0)


DECLARE @Temp3 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [SUMMA]			[numeric](19,2),
 [SUMMA_ALL]	[numeric](19,2),
 [SUMMA_M]		[numeric](19,2),
 [SUMMA_M_VKR]		[numeric](19,2)
)

INSERT INTO @Temp3 ([NUM],[LINK_PAYS],[SUMMA],[SUMMA_ALL],[SUMMA_M], SUMMA_M_VKR)
SELECT  T.[NUM], T.[LINK_PAYS],
		  [SUMMA] 	= dbo.IS_MIN((SELECT SUM(T3.SALDO * KOEF) FROM @Temp2 T3 WHERE  T3.NUM <= T.NUM AND T3.LINK_PAYS = T.LINK_PAYS),T.PREDEL), 
		  [SUMMA_ALL] 	= dbo.IS_MIN((SELECT SUM(T3.SALDO) FROM @Temp2 T3 WHERE  T3.NUM <= T.NUM AND T3.LINK_PAYS = T.LINK_PAYS),T.PREDEL),
		  [SUMMA_M] 	= CASE WHEN ABS(SUM(MP_M)) < ABS(T.SALDO) THEN ABS(T.SALDO) ELSE T.SALDO END,
		SUMMA_M_VKR 	= CASE WHEN ABS(SUM(MP_M)) < ABS(T.SALDO) THEN ABS(T.SALDO) ELSE T.SALDO END * KOEF
FROM @Temp2 T --WHERE SALDO > 0
GROUP BY T.NUM,T.PREDEL,T.SALDO,T.LINK_PAYS, KOEF 
ORDER BY T.NUM

if @FlagShow = 1  
	select num as [Месяц], LINK_PAYS as [Вычет], summa as [Скидка по ВКР/ЕКР], summa_all as [Скидка с начала года], summa_m as [Скидка за месяц]  from @Temp3


DECLARE @PREDEL_INV [numeric](15, 2)
SET @PREDEL_INV = ISNULL((SELECT TOP 1 PREDEL FROM dbo.DICTIONARY_MROT_TABLE3 DMT 
									WHERE LINK_MINROT = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_MROT 
									WHERE PERIOD <=@DATE1 ORDER BY PERIOD DESC) AND (REF_PAY = @RefPay)),0)

DECLARE @T2_1 TABLE
([NUM]			[int],
 [SUMMA]			[numeric](19, 2),
 [SUMMA_VKR]	[numeric](19, 2),
 [SUMMA_M]		[numeric](19, 2),
 [SUMMA_M_VKR]	[numeric](19, 2),
 [MP]				[numeric](19, 2),
 [MP_VKR]		[numeric](19, 2),
 [MP_M]			[numeric](19, 2),
 [MP_M_VKR]		[numeric](19, 2),
 [STATUS]		[int],
 [INV]			[numeric](19, 2))


INSERT INTO @T2_1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR],[MP],[MP_VKR],[MP_M],[MP_M_VKR],[STATUS],[INV])
SELECT T1.[NUM],T1.[SUMMA],T1.[SUMMA_VKR],T1.[SUMMA_M],T1.[SUMMA_M_VKR],
--		 [MP] 		= ISNULL((SELECT SUM(SUMMA) FROM @Temp3 T WHERE T.NUM <= T1.NUM),0),  
		 [MP] 		= ISNULL((SELECT SUM(SUMMA_ALL) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
		 [MP_VKR]	= ISNULL((SELECT SUM(SUMMA) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
		 [MP_M] 	= ISNULL((SELECT SUM(SUMMA_M) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
		 [MP_M_VKR] = ISNULL((SELECT SUM(SUMMA_M_VKR) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
--		 [MP_M_VKR] = ISNULL((SELECT SUM(SUMMA) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
		 [STATUS] 	= dbo.is_invalid(@linkFace,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,T1.NUM,@Year))), 
		 [INV] 		= cast(0 as numeric(15,2))
FROM @T1 T1 
GROUP BY T1.NUM,T1.SUMMA,T1.SUMMA_VKR,T1.SUMMA_M,T1.SUMMA_M_VKR
ORDER BY T1.NUM


DECLARE @summa_m 	[numeric](15, 2), 
		  @mp_m 		[numeric](15, 2),
		  @num 		[int], 
		  @Flag 		[bit], 
		  @itog 		[numeric](15, 2)

SET @itog = 0
DECLARE TMP_CUR CURSOR
FOR SELECT SUMMA_M, MP_M,NUM FROM @T2_1 WHERE STATUS = 2
OPEN TMP_CUR
FETCH TMP_CUR INTO @summa_m,@mp_m,@num
WHILE (@@FETCH_STATUS  = 0) AND (@PREDEL_INV - @itog) > 0 BEGIN
	IF @PREDEL_INV < (@itog+ @summa_m - @mp_m)
		UPDATE @T2_1 SET INV =(@PREDEL_INV-@itog) WHERE NUM = @num
	ELSE
		UPDATE @T2_1 SET INV =(@summa_m - @mp_m) WHERE NUM = @num
	
	SET @itog = @itog + @summa_m - @mp_m
	FETCH TMP_CUR INTO @summa_m,@mp_m,@num
END
CLOSE TMP_CUR
DEALLOCATE TMP_CUR

-- Другие льготы за месяц помимо инвалидов
---Вычеты от удержаний
select 
	TA.LINK_DED, MON = MONTH(CJ.PERIOD_BEGIN),
	SUMMA_G = CAST(0 AS NUMERIC(18,2)),
	SUMMA_M = SUM(SUMMA),
	LIMIT = ISNULL((SELECT TOP 1 PREDEL FROM @NASTR WHERE REF_PAY = TA.LINK_DED),0)
INTO #DED_U
from 
	dbo.EMPL E inner join dbo.calculate_jurnal cj on e.link = cj.link_empl
	inner join dbo.TAX2_APP TA on TA.LINK_UP = CJ.LINK_PAYS
where 
	cj.LINK_DEP = @DEP_LINK
	AND
	year(period_begin) = @Year
	and
	E.PERS_LINK = @linkPers	
	and 
	MONTH(cj.PERIOD_BEGIN) <= @Month
	and
	ISNULL(TA.LINK_DED,0) > 0
GROUP BY 
	TA.LINK_DED, MONTH(CJ.PERIOD_BEGIN)


UPDATE A
SET SUMMA_G = (SELECT SUM(SUMMA_M) FROM #DED_U B WHERE B.MON <= A.MON )
FROM #DED_U A

UPDATE #DED_U
SET 
	SUMMA_G = CASE WHEN ISNULL(SUMMA_G,0) < ISNULL(LIMIT,0) THEN ISNULL(SUMMA_G,0) ELSE ISNULL(LIMIT,0) END,
	SUMMA_M = CASE WHEN ISNULL(SUMMA_G,0) < ISNULL(LIMIT,0) THEN ISNULL(SUMMA_M,0)
				ELSE 
					CASE WHEN ISNULL(LIMIT,0) - (ISNULL(SUMMA_G,0) - ISNULL(SUMMA_M,0)) > 0 THEN 
						ISNULL(LIMIT,0) - (ISNULL(SUMMA_G,0) - ISNULL(SUMMA_M,0))
					ELSE 0
					END
			  END

UPDATE @T2_1 SET INV = ISNULL(INV,0) + ISNULL((SELECT SUM(SUMMA_M) FROM #DED_U WHERE MON = NUM),0)

--Расчет налога
--
DECLARE @T2 TABLE 
([NUM]				[int],
 [SUMMA]			[numeric](19, 2),
 [SUMMA_VKR]		[numeric](19, 2),
 [SUMMA_M]			[numeric](19, 2),
 [SUMMA_M_VKR]		[numeric](19, 2),
 [MP]				[numeric](19, 2),
 [MP_VKR]			[numeric](19, 2),
 [MP_M]				[numeric](19, 2),
 [MP_M_VKR]			[numeric](19, 2),
 [STATUS]			[int],
 [INV]				[numeric](19, 2),
 [INV_VKR]			[numeric](19, 2),
 [TARIF]			[TINYINT],
 [SPECO] [INT]
  ) -- Категория тарифа

INSERT INTO @T2 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR],[MP],[MP_VKR],[MP_M],[MP_M_VKR],[STATUS],[INV],[INV_VKR],[TARIF],[SPECO])
SELECT [NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR],[MP],[MP_VKR],[MP_M],[MP_M_VKR],[STATUS],[INV],
		 [INV_VKR] = (CASE WHEN (SUMMA_M - MP_M) = 0 THEN 0 ELSE (SUMMA_M_VKR - MP_M_VKR)*INV/(SUMMA_M - MP_M) END),
		 TARIF = CASE WHEN dbo.is_invalid(@linkFace,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,NUM,@Year))) = 2 THEN 3 ELSE @TARIF END,
		 [SPECO] = (SELECT TOP 1 [COD_SPO_USL_TRUD] FROM #PERIODY 
						WHERE dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,NUM,@Year)) BETWEEN st_date1 AND st_date2
						AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,NUM,@Year)) BETWEEN im_date1 AND im_date2)
FROM 
	@T2_1

if @FlagShow = 1 
	select [num] as [Месяц], [summa] as [Сумма с Н/Г],summa_vkr as [Сумма с Н/Г по ВКР/ЕКР], summa_m as [За мес], 
	summa_m_vkr as [За мес.по ВКР/ЕКР], mp as [Ск.всего], mp_vkr as [Ск.всего по ВКР/ЕКР],mp_m as [Ск. за мес],
	mp_m_vkr as [Ск.за мес.по ВКР/ЕКР], inv as [Льготы], inv_vkr as [Льготы по ВКР/ЕКР], TARIF as [ТАРИФ], [SPECO]  from @T2


DECLARE @WAY_CALC [int]
SELECT @WAY_CALC = WAY_CALC FROM dbo.PAYS WHERE LINK = @RefPay

DECLARE @Pred table  
(
 TARIF TINYINT,	
 [PREDEL]  [numeric](15, 2), 
 [PERCENT] [numeric](8, 2),
 WAY_CALC TINYINT,
 SPECO INT,
 NSPECO VARCHAR(254) )

IF @WAY_CALC<5
	
	IF @FlagMS = 1
		INSERT INTO @Pred (TARIF, [PREDEL],[PERCENT],SPECO,NSPECO)
		SELECT TARIF, [PREDEL],[PERCENT],SPECO=0,NSPECO='' FROM dbo.DICTIONARY_RANGE D
		WHERE
			(LINK_PAYS = @RefPay) 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE D1 WHERE D1.TARIF = D.TARIF AND (LINK_PAYS = @RefPay) AND DATE < @DATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
	ELSE 
		INSERT INTO @Pred (TARIF, [PREDEL],[PERCENT],SPECO,NSPECO)
		SELECT TOP 1 TARIF, [PREDEL] = 999999999999, [PERCENT],SPECO=0,NSPECO='' 
		FROM dbo.DICTIONARY_RANGE D
		WHERE 
			(LINK_PAYS = @RefPay) 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE D1 WHERE D1.TARIF = D.TARIF AND (LINK_PAYS = @RefPay) AND DATE < @DATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
ELSE 
BEGIN	
		
	DECLARE @Sex 		[int], 
			  @YearB 	[int], 
			  @Type 		[int]

	SELECT @Sex = SEX, @YearB = CASE WHEN RESIDENT = 1 THEN ISNULL(YEAR(BIRTHDATE),0) 
												ELSE 1966 END -- иностранцы по тарифам как для 66 года и страрше
											FROM dbo.PERSON WHERE LINK =@linkFace
	SET 	@Type = (CASE WHEN (@Sex = 1 AND @YearB < 1953) OR (@Sex = 2 AND @YearB<1957) THEN 1
						WHEN (@Sex = 1 AND @YearB BETWEEN 1953 AND 1966) OR (@Sex = 2 AND  @YearB BETWEEN 1957 AND 1966) THEN 2 
						ELSE 3 END)

	IF @FlagMS = 1 
		INSERT INTO @Pred (TARIF, [PREDEL],[PERCENT],WAY_CALC,SPECO,NSPECO)
		SELECT 
			TARIF,  
			[PREDEL],
			[PERCENT] = (CASE WHEN @Type = 1 THEN PERCENT1 WHEN @Type = 2 THEN PERCENT2 ELSE PERCENT3 END),
			WAY_CALC,
			SPECO,
			NSPECO
		FROM 
			dbo.DICTIONARY_RANGE_PF D
		WHERE
			LINK_PAYS = @RefPay 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND ISNULL(D1.SPECO,0) = ISNULL(D.SPECO,0) AND LINK_PAYS = @RefPay AND DATE < @DATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
	ELSE 
		INSERT INTO @Pred (TARIF, [PREDEL],[PERCENT],WAY_CALC,SPECO,NSPECO)
		SELECT TOP 1 
			TARIF, 
			[PREDEL] = 999999999999,
			[PERCENT] = (CASE WHEN @Type = 1 THEN PERCENT1 WHEN @Type = 2 THEN PERCENT2 ELSE PERCENT3 END),
			WAY_CALC,
			SPECO,NSPECO
		FROM 
			dbo.DICTIONARY_RANGE_PF D
		WHERE
			LINK_PAYS = @RefPay 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND ISNULL(D1.SPECO,0) = ISNULL(D.SPECO,0) AND LINK_PAYS = @RefPay AND DATE < @DATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
	END

IF @FlagShow = 1 
	select TARIF as [Тариф], Predel as [Предел], [Percent] as [Процент], NSPECO AS [Спецоценка] from @Pred P
	WHERE EXISTS (SELECT * FROM @T2 B WHERE B.TARIF = P.TARIF AND ISNULL(B.[SPECO],0) = ISNULL(P.[SPECO],0))

DECLARE @res TABLE
([NUM]			[int],
 [SUMMA]		[numeric] (19, 2),
 [SUMMA_M_VKR]	[numeric] (19, 2),
 [PERC]			[numeric] (19, 2),
 [SUM_MON]		[numeric] (19, 2),
 [TARIF]		INT,
 [SPECO]		INT)

INSERT INTO @res([NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],[TARIF],[SPECO])
SELECT T7.[NUM],T7.[SUMMA],T7.[SUMMA_M_VKR],T7.[PERC], CAST(0 as numeric(15,2)) AS SUM_MON, [TARIF], [SPECO]
FROM  
	(
	SELECT 
		[NUM], 
		[SUMMA] 		 = SUMMA - MP, 
		[SUMMA_M_VKR] = SUMMA_M_VKR - MP_M_VKR,	
		[PERC] 		 = ISNULL((SELECT TOP 1 T.[PERCENT] FROM (SELECT TOP 1 * FROM @Pred P WHERE B.TARIF = P.TARIF AND ISNULL(B.SPECO,0) = ISNULL(P.[SPECO],0) AND PREDEL > (SUMMA - MP + @SUM_DGH) ORDER BY PREDEL) T),0),
		B.[TARIF],
		B.[SPECO]
	 FROM @T2	B
	 UNION
	 SELECT DISTINCT
		[NUM] 			= ISNULL((SELECT MIN(NUM) FROM @T2 B1 WHERE B1.TARIF = B.TARIF AND ISNULL(B1.[SPECO],0) = ISNULL(B.[SPECO],0) AND (SUMMA-MP+@SUM_DGH) > PREDEL),12), 
		[SUMMA] 		= PREDEL - @SUM_DGH, 
		[SUMMA_M_VKR]= 0, 
		[PERC] 		= [PERCENT],  
		B.[TARIF],
		B.[SPECO]		
 	 FROM 
 		@T2 B INNER JOIN @Pred T ON B.TARIF = T.TARIF AND ISNULL(B.[SPECO],0) = ISNULL(T.[SPECO],0)
 	 WHERE 
 		PREDEL < (SELECT TOP 1 (SUMMA - MP + @SUM_DGH) FROM @T2 B1 WHERE B1.TARIF = B.TARIF AND ISNULL(B1.[SPECO],0) = ISNULL(B.[SPECO],0) ORDER BY 1 DESC)
 	) T7


DECLARE Curs CURSOR FAST_FORWARD FOR
SELECT NUM,SUMMA FROM @res ORDER BY [NUM]  

DECLARE @Summa [numeric] (19, 2), 
	@summa_prev [numeric] (19, 2), 
	@num1 [int]


SET @summa_prev = 0
OPEN Curs
FETCH NEXT FROM Curs INTO @num1, @Summa
WHILE @@FETCH_STATUS = 0 BEGIN
	UPDATE @res SET SUM_MON = @Summa - @summa_prev WHERE NUM = @num1 AND SUMMA = @Summa
	SET @summa_prev = @Summa
  	FETCH NEXT FROM Curs INTO @num1, @Summa
END
CLOSE Curs
DEALLOCATE Curs

DECLARE @Result1 TABLE
([NUM]			[int],
 [SUMMA]			[numeric] (19, 2),
 [SUMMA_M_VKR]	[numeric] (19, 2),
 [PERC]			[numeric] (19, 2),
 [SUM_MON]		[numeric] (19, 2),
 [SKIDKA]		[numeric] (19, 2),
 [KOEF]			[numeric] (19, 10), 
 [TARIF]		INT,
 [SPECO]		INT)


INSERT INTO @Result1 ([NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],[SKIDKA],[KOEF], [TARIF], [SPECO])
SELECT [NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],
		 [SKIDKA] = dbo.is_min(T1.SUM_MON, ISNULL((SELECT INV FROM @T2 T4  WHERE T4.NUM = T1.NUM),0)  
						- ISNULL((SELECT SUM(T3.SUM_MON) FROM @res T3 WHERE T3.NUM = T1.NUM AND T3.SUMMA < T1.SUMMA), 0)),
		 [KOEF] = (SELECT (CASE WHEN (SUMMA_M - MP_M) = 0 THEN 0 ELSE (SUMMA_M_VKR - MP_M_VKR)/(SUMMA_M - MP_M) END) FROM @T2 T2 WHERE T2.NUM = T1.NUM),
		 [TARIF], [SPECO]
FROM @res T1

DECLARE @RESULT TABLE
([NUM]			[int],
 [SUMMA]			[numeric] (19, 2),
 [SUMMA_M_VKR]	[numeric] (19, 2),
 [PERC]			[numeric] (19, 2),
 [SUM_MON]		[numeric] (19, 2),
 [SKIDKA]		[numeric] (19, 2),
 [KOEF]			[numeric] (19, 10),
 [VYCH] 		[numeric] (19, 2),
 [TARIF]		INT,
 [SPECO]		INT)

INSERT INTO @RESULT ([NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],[SKIDKA],[KOEF], [TARIF], [SPECO])
SELECT [NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],
		 [SKIDKA] = (CASE WHEN SKIDKA < 0 THEN 0 ELSE SKIDKA END),
		 [KOEF], [TARIF], [SPECO]
FROM @Result1

DECLARE @Razn 			[numeric](15, 2), 
	  @NalCurr 	[numeric](15, 2),
	  @Sum1 		[numeric](15, 2)

--Расчет с копейками
SET @NalCurr = (SELECT sum(ROUND((PERC * (COALESCE(SUM_MON,0) - COALESCE(SKIDKA,0))* COALESCE(KOEF,0)/100) * 100, 2) / 100) FROM @RESULT )

--Сумма ранее начисленного взноса
SET @Sum1 = ISNULL((SELECT SUM(SJ.SUMMA) FROM dbo.S_J_C_Short SJ 
WHERE SJ.LINK_VKR = @LinkVKR 
	--AND ( (SJ.LINK_EKR IN (@LINK_EKR,@LINK_EKR_ADD) AND @LINK_EKR <> @LINK_211EKR) OR (@LINK_EKR = @LINK_211EKR AND SJ.LINK_EKR IN (@LINK_211EKR,@LINK_213EKR)) )
	AND ( (SJ.LINK_EKR IN (@LINK_EKR,@LINK_EKR_ADD) AND @LINK_EKR <> @LINK_211EKR) OR (@LINK_EKR = @LINK_211EKR AND SJ.LINK_EKR = @LINK_EKR) )
	AND SJ.LINK_PAYS = @RefPay 
	AND (SJ.LINK_FACE = @linkFace) 
	AND MONTH_BEGIN <= @Month 
	AND YEAR_BEGIN=@Year 
	AND sj.LINK_DEP = @DEP_LINK),0)

--IF --ЕСЛИ ГОДОВОЙ ДОХОД ПО ВСЕМ ИСТОЧНИКАМ < 0
--	(SELECT SUM(SUMMA) FROM @RESULT) < 0 
--		--AND @Sum1 = 0 
--		-- И ЕСЛИ ТЕКУЩИЙ НАЛОГ ПОЛУЧАЕТСЯ < 0
--		AND @NalCurr < 0
--	SET @NalCurr = 0
	
SET @Razn = @NalCurr - @Sum1

DECLARE @FLG INT
SELECT TOP 1 @FLG = ISNULL(CONVERT(INT,VALUE),0) 
FROM S_OPTIONS WHERE OBJECT = (SELECT TOP 1 LINK FROM S_OBJECTS WHERE CODE = 'ESN_OPTIONS_FLG') AND SID IS NULL

IF @Razn <0 AND @FLG = 0
	SET @Razn=0

SELECT [SUMMA] 		= ISNULL(SUMMA_VKR,0), 
	 [SUMMA_VKR] 	= ISNULL(SUMMA_M_VKR, 0),
	 [SUM_DED] 		=	CASE WHEN ISNULL(SUMMA_VKR, 0) > 0 
						THEN
							ISNULL((SELECT TOP 1 MP_VKR FROM @T2 WHERE NUM = @Month), 0)
						ELSE 0 END,	
	 [INV_M] 		= CASE WHEN ISNULL(SUMMA_VKR, 0) > 0 
						THEN
							ISNULL((SELECT SUM(SKIDKA*KOEF) FROM @RESULT WHERE NUM = @Month),0)
						ELSE 0 END,
	 [INV] 			= CASE WHEN ISNULL(SUMMA_VKR, 0) > 0 
						THEN
							ISNULL((SELECT SUM(SKIDKA*KOEF) FROM @RESULT WHERE NUM <= @Month),0)
						ELSE 0 END,
	 [DED_M] 		= CASE WHEN ISNULL(SUMMA_VKR, 0) > 0 
						THEN
							ISNULL((SELECT TOP 1 MP_M_VKR FROM @T2 WHERE NUM = @Month), 0)
						ELSE 0 END,
	 [PERC]			= ISNULL((SELECT MIN(PERC) FROM @RESULT WHERE NUM = @Month),0),
	 [NALOG] 		= @NalCurr, 
	 [NAL_DED] 		= @Sum1, 
	 [NAL_CUR] 		= @Razn,
	 [TARIF]		= ISNULL((SELECT MIN([TARIF]) FROM @RESULT WHERE NUM = @Month),0), 
	 [SPECO]		= ISNULL((SELECT MIN([SPECO]) FROM @RESULT WHERE NUM = @Month),0),
	 [NSPECO]		= (SELECT TOP 1 CODE FROM dbo.SZV4_SPR WHERE LINK = ISNULL((SELECT MIN([SPECO]) FROM @RESULT WHERE NUM = @Month),0) )
FROM 
	@T1 
WHERE 
	NUM = @Month

SET NOCOUNT OFF





GO


GRANT EXECUTE ON dbo.[SALARY_FILL_DED_ESN_VKR] TO PUBLIC

GO


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


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[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),
				KBK = left(replace(isnull(KBK1.CODE, KBK.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),'.',''), 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),
				KBK = left(replace(isnull(KBK1.CODE, KBK.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.[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(100),
                              [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(100)' 
                                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(100)),4)+'''),'$CODE3$','''+RIGHT(''000''+CAST(ROW_NUMBER() OVER (ORDER BY [ORDERS],[CODE]) AS VARCHAR(100)),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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

CREATE           
PROCEDURE FB_EXPORT_ZF
	@cBuffId	varchar(30) = '',
	@cObjCode	varchar(30) = '',
	@cFormat	varchar(30) = ''
AS
  DECLARE @iDepLink	int

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


-- Таблица 2 (FROM)
SELECT 	KOD_BP 	= BUDG,
	NAME_BP = FULL_NAME
from dbo.DEPARTMENTS
where LINK = @iDepLink


-- Таблица 3 (TO)
SELECT 	KOD_FO 	= DFO.BUDG,
	NAME_FO = DFO.FULL_NAME
from dbo.DEPARTMENTS D
inner join dbo.DEPARTMENTS DFO on D.FO_LINK = DFO.LINK
where D.LINK = @iDepLink


if @cFormat >= '2011.01'
begin
	declare @iPeriodNum tinyint 
	if @cObjCode = 'FB_ZAYAVKA'
		select @iPeriodNum = PERIOD from dbo.FB_ZAYAVKA_OPTIONS
	else
		if @cObjCode = 'FB_PLAN_D'
			select @iPeriodNum = PERIOD from dbo.FB_PLAN_D_OPTIONS
		else
			select @iPeriodNum = PERIOD from dbo.FB_PLAN_OPTIONS
	
	-- Таблица 4 (ZF)
	SELECT	G.LINK,
			LINK_UP	    = G.LINK,
			G.NUMBER,
			[GUID]	= '',
			[DATE] 	    = G.[DATE],
			[DATE_EXEC] = G.[DATE_PROV],
			[DATE_BEGIN] = case @iPeriodNum when 1 then G.[DATE_PROV] else NULL end,
			G.SUMMA,
			ACC_SEND = DA.ACC_CODE ,
			ANALITICS = '',
			PERIOD = case @iPeriodNum when 1 then 'Y' when 2 then 'Q' else 'M' end,
			NAME_BUD = BUDG_NAME,
			KOD_BP = DA.DEP_B_CODE,
			NAME_BP = DA.DEP_FNAME
	FROM dbo.G_PROV G
	inner join dbo.BB_DEP_ACC_DOP(NULL) DA on DA.ACC_LINK = G.ACC
	where G.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId))



	-- Таблица 4 (KPST)
	select	KOD_BP = Z.DEP_CODE,
			ACC_RCP = Z.ACC_CODE,
			NAME_BP = Z.DEP_NAME,
			GLAVA	  = isnull(VKR.CODE_FKR_M,''),
			RAZDEL	  = isnull(VKR.CODE_FKR_D,''),
			STATIA	  = isnull(VKR.CODE_FKR_T,''),
			VID	  = isnull(VKR.CODE_FKR_E,''),
			E_KLASS	  = case KBK.TYPE when 1 then convert (varchar(3), EKR.CODE) else '' end,
			--KKIVNF	  = case KBK.TYPE when 3 then replace(KBK.CODE,'.','') + convert (varchar(3), EKR.CODE) else '' end,
			--KKIVF	  = case KBK.TYPE when 4 then replace(KBK.CODE,'.','') + convert (varchar(3), EKR.CODE) else '' end,
			--KDOH	  = case KBK.TYPE when 2 then replace(KBK.CODE,'.','') + convert (varchar(3), EKR.CODE) else '' end,
			KKIVNF	  = case KBK.TYPE when 3 then replace(KBK.CODE,'.','') else '' end,
			KKIVF	  = case KBK.TYPE when 4 then replace(KBK.CODE,'.','') else '' end,
			KDOH	  = case KBK.TYPE when 2 then replace(KBK.CODE,'.','') else '' end,
			ADD_KLASS = convert (varchar(20), DCL.CODE),
			[LOCAL]   = '',
			SUMMA	  = ZS.P1 + ZS.P2 + ZS.P3 + ZS.P4 + ZS.P5 + ZS.P6 + ZS.P7 + ZS.P8 + ZS.P9 + ZS.P10 + ZS.P11 + ZS.P12,
			SUMMA1	  = case @iPeriodNum when 3 then ZS.P1
										 when 2 then ZS.P1 + ZS.P2 + ZS.P3
										 else ZS.P1 + ZS.P2 + ZS.P3 + ZS.P4 + ZS.P5 + ZS.P6 + ZS.P7 + ZS.P8 + ZS.P9 + ZS.P10 + ZS.P11 + ZS.P12 end,			
			SUMMA2	  = case @iPeriodNum when 3 then ZS.P2 when 2 then ZS.P4 + ZS.P5 + ZS.P6 else 0 end,			
			SUMMA3	  = case @iPeriodNum when 3 then ZS.P3 when 2 then ZS.P7 + ZS.P8 + ZS.P9 else 0 end,			
			SUMMA4	  = case @iPeriodNum when 3 then ZS.P4 when 2 then ZS.P10 + ZS.P11 + ZS.P12 else 0 end,			
			SUMMA5	  = case @iPeriodNum when 3 then ZS.P5 else 0 end,			
			SUMMA6	  = case @iPeriodNum when 3 then ZS.P6 else 0 end,			
			SUMMA7	  = case @iPeriodNum when 3 then ZS.P7 else 0 end,			
			SUMMA8	  = case @iPeriodNum when 3 then ZS.P8 else 0 end,			
			SUMMA9	  = case @iPeriodNum when 3 then ZS.P9 else 0 end,			
			SUMMA10	  = case @iPeriodNum when 3 then ZS.P10 else 0 end,			
			SUMMA11	  = case @iPeriodNum when 3 then ZS.P11 else 0 end,			
			SUMMA12	  = case @iPeriodNum when 3 then ZS.P12 else 0 end,			
			PRIM_STR  = ZS.COMMENT,
			NUM_BO	  = ZS.BO,
			LINK	  = ZS.LINK,
			LINK_UP	  = ZS.LINK_UP
	from dbo.FINANSE ZS
	inner join dbo.FB_ZAYAVKA Z on Z.LINK = ZS.LINK_UP
	inner join dbo.BI_DICTION_KBK KBK on KBK.LINK = ZS.VKR
	inner join dbo.KOSGU EKR on EKR.LINK = ZS.EKR
	left join dbo.BI_DICTION_VKR VKR on VKR.LINK = ZS.VKR
	left join dbo.DOP_CLASSIF DCL on DCL.LINK = ZS.DOP_CL
	where ZS.LINK_UP in (select LINK from dbo.BufferGetTableByID(@cBuffId))
end
else
begin
-- Таблица 4 (ZF)
if @cObjCode = 'FB_ZAYAVKA'
	SELECT  LINK 	 = Z.LINK,
		LINK_UP	 = Z.LINK,
		NUMBER   = Z.NUMBER,
		[DATE] 	 = Z.[DATE],
		SUMMA 	 = Z.SUMMA,
		KOD_BP 	 = D.BUDG,
		ACC_SEND = Z.OACC_CODE, 
		NAME_BP  = Z.ODEP_NAME,
		ANALITICS= '',
		DATE_EXEC= Z.DATE_PROV
	FROM dbo.FB_ZAYAVKA Z
	inner join dbo.DEPARTMENTS D on Z.ODEP_LINK = D.LINK 
	where Z.LINK in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())

if @cObjCode = 'FB_ZAYAVKA_S'
	SELECT  LINK 	 = Z.LINK,
		LINK_UP	 = Z.LINK,
		NUMBER   = Z.NUMBER,
		[DATE] 	 = Z.[DATE],
		SUMMA 	 = Z.SUMMA,
		KOD_BP 	 = D.BUDG,
		ACC_SEND = Z.ACC_CODE, 
		NAME_BP  = Z.DEP_NAME,
		ANALITICS= '',
		DATE_EXEC= Z.DATE_PROV
	FROM dbo.FB_ZAYAVKA_S Z
	inner join dbo.DEPARTMENTS D on Z.DEP_LINK = D.LINK 
	where Z.LINK in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())



-- Таблица 4 (ZFST)
if @cObjCode = 'FB_ZAYAVKA'
	select  KOD_BP 	  = D.BUDG,
		ACC_RCP   = Z.PACC_CODE, 
		NAME_BP   = Z.PDEP_NAME,	
		GLAVA	  = VKR.CODE_FKR_M,
		RAZDEL	  = VKR.CODE_FKR_D,
		STATIA	  = VKR.CODE_FKR_T,
		VID	  = VKR.CODE_FKR_E,
		E_KLASS	  = convert (varchar(3), EKR.CODE),
		KKIVNF	  = '',
		KKIVF	  = '',
		KOD_DOH	  = '',
		ADD_KLASS = convert (varchar(20), DCL.CODE),
		SUMMA	  = ZS.SUMMA,
		PRIM_STR  = ZS.TITLE,
		[LOCAL]	  = '',	
		LINK	  = ZS.LINK,
		LINK_UP	  = ZS.LINK_UP
	from dbo.FINANSE_PLAN_SUMM ZS
	inner join dbo.FB_ZAYAVKA Z on Z.LINK = ZS.LINK_UP
	inner join dbo.DEPARTMENTS D on Z.PDEP_LINK = D.LINK 
	inner join dbo.BI_DICTION_VKR VKR on VKR.LINK = ZS.VKR
	inner join dbo.KOSGU EKR on EKR.LINK = ZS.EKR
	left join dbo.DOP_CLASSIF DCL on DCL.LINK = ZS.DOP_CL
	where ZS.LINK_UP in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())

if @cObjCode = 'FB_ZAYAVKA_S'
	select	KOD_BP 	  = D.BUDG,
		ACC_RCP   = DA.CODE, 
		NAME_BP   = D.[NAME],	
		GLAVA	  = VKR.CODE_FKR_M,
		RAZDEL	  = VKR.CODE_FKR_D,
		STATIA	  = VKR.CODE_FKR_T,
		VID	  = VKR.CODE_FKR_E,
		E_KLASS	  = convert (varchar(3), EKR.CODE),
		KKIVNF	  = '',
		KKIVF	  = '',
		KOD_DOH	  = '',
		ADD_KLASS = convert (varchar(20), DCL.CODE),
		SUMMA	  = T.SUMMA,
		PRIM_STR  = T.TITLE,
		[LOCAL]	  = '',	
		LINK	  = 0,
		LINK_UP	  = T.LINK_UP
	FROM (	select 	LINK_UP  = Z.LINK_REESTR,
			ACC_LINK = Z.PACC_LINK, 
			ZT.DOP_CL, 
			ZT.EKR, 
			ZT.VKR,
			ZT.TITLE,
			SUMMA = sum(ZT.SUMMA)
		from dbo.FB_ZAYAVKA Z
		inner join dbo.FB_PLAN_TABLE ZT on ZT.LINK_UP = Z.LINK
		where Z.LINK_REESTR in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())
		group by Z.PACC_LINK, ZT.DOP_CL, ZT.EKR, ZT.VKR, ZT.TITLE, Z.LINK_REESTR) T
	inner join dbo.DICTIONARY_ACCOUNTS DA ON DA.LINK  = T.ACC_LINK
	inner join dbo.DEPARTMENTS D ON D.LINK   = DA.REF_LINK_D
	inner join dbo.BI_DICTION_VKR VKR ON VKR.LINK = T.VKR
	inner join dbo.DICTIONARY_ITEM EKR ON EKR.LINK = T.EKR
	left JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = T.DOP_CL

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.[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.[KJ_VACATION_GRAPHICS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KJ_VACATION_GRAPHICS]

GO
/*******************************************************************************

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

*******************************************************************************/
CREATE PROCEDURE [dbo].KJ_VACATION_GRAPHICS
	@LINK_DOC int,
	@MONTH_MASK varchar(13),
	@ORG_ALL int,
	@OTBOR_LINK int
AS
CREATE TABLE #RECORDS(LINK INT)
IF EXISTS(SELECT * FROM OBJECT_VAR_SUBDIV_HEAD WHERE LINK_UP = @OTBOR_LINK)
	INSERT	INTO #RECORDS
	SELECT RECORD AS LINK
	FROM OBJECT_VAR_SUBDIV_HEAD
	WHERE LINK_UP = @OTBOR_LINK
ELSE
	INSERT	INTO #RECORDS
	SELECT	LINK FROM SUBDIVISION(DEFAULT)
	WHERE	DELETED = 0



SELECT	VGT.LINK,
	VG.NUMBER as number,
	VG.DATE as date_doc,
	VG.PERIOD as period,
	D.FULL_NAME as dep_name,
	VGT.EMPL_LINK as empl_link,
	isnull(VGT.SUBDIV_NAME,'') as podr,
	VGT.SUBDIV_HEAD as podr_link,
	VGT.DOLJNOST as doljn,
	VGT.TAB as tab_num,
	VGT.FIO as fio,
	VGT.DATE_BEGIN as date_begin,
	VGT.DATE_END as date_end,
	ISNULL(datediff(Day,VGT.DATE_BEGIN,VGT.DATE_END) - dbo.SA_HOLIDAY_COUNT_FN(isnull(VGT.DATE_BEGIN,'19000101'),isnull(VGT.DATE_END,'19000101'))+1,'') as len_day,
	IV.DATE_BEGIN as DATE_FAKT
FROM	dbo.VAC_GRAPHIC VG INNER JOIN dbo.VAC_GRAPHIC_TABLE VGT
	ON VG.LINK = VGT.DOC_LINK LEFT JOIN dbo.DEPARTMENTS D
	ON VG.LINK_DEP = D.LINK LEFT JOIN dbo.ITEM_VACATION IV
	ON VGT.ORDER_ITEMS_LINK = IV.LINK
	inner join sd_empl sd ON  sd.link =  VGT.EMPL_LINK and sd.date_begin is not null
WHERE	((@ORG_ALL = 1 AND VGT.SUBDIV_HEAD IN (SELECT LINK FROM #RECORDS) AND VG.PERIOD = (SELECT PERIOD FROM VAC_GRAPHIC WHERE LINK = @LINK_DOC))
  		OR (@ORG_ALL = 0 AND VG.LINK = @LINK_DOC))
	AND ((SUBSTRING(@MONTH_MASK,MONTH(VGT.DATE_BEGIN),1) = '1' OR SUBSTRING(@MONTH_MASK,MONTH(VGT.DATE_END),1) = '1')
		OR (SUBSTRING(@MONTH_MASK,13,1) = '1'))
ORDER	BY VGT.SUBDIV_CODE, VGT.FIO


DROP TABLE #RECORDS



GO


GRANT EXECUTE ON dbo.[KJ_VACATION_GRAPHICS] 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_KP]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[FB_EXPORT_KP]

GO


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

CREATE           
PROCEDURE [dbo].FB_EXPORT_KP
	@cBuffId	varchar(30) = '',
	@cObjCode	varchar(30) = '',
	@cFormat	varchar(30) = ''

AS
  DECLARE @iDepLink	int

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


-- Таблица 2 (FROM)
SELECT 	KOD_BP 	= BUDG,
	NAME_BP = FULL_NAME,
	LINK	= 0,
	LINK_UP	= 0
from dbo.DEPARTMENTS
where LINK = @iDepLink


-- Таблица 3 (TO)
SELECT 	KOD_FO 	= DFO.BUDG,
	NAME_FO = DFO.FULL_NAME,
	LINK	= 0,
	LINK_UP	= 0
from dbo.DEPARTMENTS D
inner join dbo.DEPARTMENTS DFO on D.FO_LINK = DFO.LINK
where D.LINK = @iDepLink


if @cFormat >= '2011.01'
begin
	declare @iPeriodNum tinyint 
	if @cObjCode = 'FB_PLAN_D'
		select @iPeriodNum = PERIOD from dbo.FB_PLAN_D_OPTIONS
	else
		select @iPeriodNum = PERIOD from dbo.FB_PLAN_OPTIONS
	
	-- Таблица 4 (ZF)
	SELECT	G.LINK,
			LINK_UP	    = G.LINK,
			[GUID]	= '',
			G.NUMBER,
			[DATE] 	    = G.[DATE],
			[DATE_EXEC] = G.[DATE_PROV],
			[DATE_BEGIN] = case @iPeriodNum when 1 then G.[DATE_PROV] else NULL end,
			G.SUMMA,
			ACCOUNT = case @cObjCode when 'FB_PLAN_D' then DA.K_ACC_CODE else DA.ACC_CODE end,
			ANALITICS = '',
			PERIOD = case @iPeriodNum when 1 then 'Y' when 2 then 'Q' else 'M' end,
			NAME_BUD = BUDG_NAME,
			KOD_BP = DA.DEP_B_CODE
	FROM dbo.G_PROV G
	inner join dbo.BB_DEP_ACC_DOP(NULL) DA on DA.ACC_LINK = G.ACC
	where G.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId))



	-- Таблица 4 (KPST)
	select	GLAVA	  = isnull(VKR.CODE_FKR_M,''),
			RAZDEL	  = isnull(VKR.CODE_FKR_D,''),
			STATIA	  = isnull(VKR.CODE_FKR_T,''),
			VID	  = isnull(VKR.CODE_FKR_E,''),
			E_KLASS	  = case KBK.TYPE when 1 then convert (varchar(3), EKR.CODE) else '' end,
			--KKIVNF	  = case KBK.TYPE when 3 then replace(KBK.CODE,'.','') + convert (varchar(3), EKR.CODE) else '' end,
			--KKIVF	  = case KBK.TYPE when 4 then replace(KBK.CODE,'.','') + convert (varchar(3), EKR.CODE) else '' end,
			--KDOH	  = case KBK.TYPE when 2 then replace(KBK.CODE,'.','') + convert (varchar(3), EKR.CODE) else '' end,
			KKIVNF	  = case KBK.TYPE when 3 then replace(KBK.CODE,'.','') else '' end,
			KKIVF	  = case KBK.TYPE when 4 then replace(KBK.CODE,'.','') else '' end,
			KDOH	  = case KBK.TYPE when 2 then replace(KBK.CODE,'.','') else '' end,
			ADD_KLASS = convert (varchar(20), DCL.CODE),
			[LOCAL]   = '',
			SUMMA	  = ZS.P1 + ZS.P2 + ZS.P3 + ZS.P4 + ZS.P5 + ZS.P6 + ZS.P7 + ZS.P8 + ZS.P9 + ZS.P10 + ZS.P11 + ZS.P12,
			SUMMA1	  = case @iPeriodNum when 3 then ZS.P1
										 when 2 then ZS.P1 + ZS.P2 + ZS.P3
										 else ZS.P1 + ZS.P2 + ZS.P3 + ZS.P4 + ZS.P5 + ZS.P6 + ZS.P7 + ZS.P8 + ZS.P9 + ZS.P10 + ZS.P11 + ZS.P12 end,			
			SUMMA2	  = case @iPeriodNum when 3 then ZS.P2 when 2 then ZS.P4 + ZS.P5 + ZS.P6 else 0 end,			
			SUMMA3	  = case @iPeriodNum when 3 then ZS.P3 when 2 then ZS.P7 + ZS.P8 + ZS.P9 else 0 end,			
			SUMMA4	  = case @iPeriodNum when 3 then ZS.P4 when 2 then ZS.P10 + ZS.P11 + ZS.P12 else 0 end,			
			SUMMA5	  = case @iPeriodNum when 3 then ZS.P5 else 0 end,			
			SUMMA6	  = case @iPeriodNum when 3 then ZS.P6 else 0 end,			
			SUMMA7	  = case @iPeriodNum when 3 then ZS.P7 else 0 end,			
			SUMMA8	  = case @iPeriodNum when 3 then ZS.P8 else 0 end,			
			SUMMA9	  = case @iPeriodNum when 3 then ZS.P9 else 0 end,			
			SUMMA10	  = case @iPeriodNum when 3 then ZS.P10 else 0 end,			
			SUMMA11	  = case @iPeriodNum when 3 then ZS.P11 else 0 end,			
			SUMMA12	  = case @iPeriodNum when 3 then ZS.P12 else 0 end,			
			PRIM_STR  = '',
			LINK	  = ZS.LINK,
			LINK_UP	  = ZS.LINK_UP
	from dbo.FINANSE ZS
	inner join dbo.BI_DICTION_KBK KBK on KBK.LINK = ZS.VKR
	inner join dbo.KOSGU EKR on EKR.LINK = ZS.EKR
	left join dbo.BI_DICTION_VKR VKR on VKR.LINK = ZS.VKR
	left join dbo.DOP_CLASSIF DCL on DCL.LINK = ZS.DOP_CL
	where ZS.LINK_UP in (select LINK from dbo.BufferGetTableByID(@cBuffId))
end
else
begin
	-- Таблица 4 (ZF)
	SELECT  G.LINK,
		LINK_UP	    = G.LINK,
		G.NUMBER,
		[DATE] 	    = G.[DATE],
		[DATE_EXEC] = G.[DATE_PROV],
		G.SUMMA,
		ACCOUNT	    = case SO.CODE when 'FB_PLAN_D' then DA.K_ACC_CODE else DA.CODE end
	FROM dbo.G_PROV G
	inner join dbo.S_OBJECTS SO on SO.LINK = G.OBJECT
	inner join dbo.DICTIONARY_ACCOUNTS DA on DA.LINK = G.ACC
	where G.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId))



	-- Таблица 4 (ZFST)
	select  GLAVA	  = isnull(VKR.CODE_FKR_M,''),
		RAZDEL	  = isnull(VKR.CODE_FKR_D,''),
		STATIA	  = isnull(VKR.CODE_FKR_T,''),
		VID	  = isnull(VKR.CODE_FKR_E,''),
		E_KLASS	  = convert (varchar(3), EKR.CODE),
		KKIVNF	  = case KBK.TYPE when 3 then replace(KBK.CODE,'.','') + convert (varchar(3), EKR.CODE) else '' end,
		KKIVF	  = case KBK.TYPE when 4 then replace(KBK.CODE,'.','') + convert (varchar(3), EKR.CODE) else '' end,
		KOD_DOH	  = case KBK.TYPE when 2 then replace(KBK.CODE,'.','') + convert (varchar(3), EKR.CODE) else '' end,
		ADD_KLASS = convert (varchar(20), DCL.CODE),
		SUMMA	  = ZS.P1 + ZS.P2 + ZS.P3 + ZS.P4 + ZS.P5 + ZS.P6 + ZS.P7 + ZS.P8 + ZS.P9 + ZS.P10 + ZS.P11 + ZS.P12,
		PRIM_STR  = '',--ZS.TITLE,
		[LOCAL]   = '',
		LINK	  = ZS.LINK,
		LINK_UP	  = ZS.LINK_UP
	from dbo.FINANSE ZS
	inner join dbo.BI_DICTION_KBK KBK on KBK.LINK = ZS.VKR
	inner join dbo.KOSGU EKR on EKR.LINK = ZS.EKR
	left join dbo.BI_DICTION_VKR VKR on VKR.LINK = ZS.VKR
	left join dbo.DOP_CLASSIF DCL on DCL.LINK = ZS.DOP_CL
	where ZS.LINK_UP in (select LINK from dbo.BufferGetTableByID(@cBuffId))
end



GO


GRANT EXECUTE ON dbo.[FB_EXPORT_KP] TO PUBLIC

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
GRANT execute on dbo.FB_EXPORT_KP 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(30),
		@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(30),
		@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(30), 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(30), 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,
			BKS.KBK_TYPE_DT, 
			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,
			BKS.KBK_TYPE_KT, 
			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 'В справочнике КБК не найден КБК: ' + KBK_CODE_DT as txt,1 ,1,0
		from #PROV_BKS
		where KBK_CODE_DT not in (select replace(CODE,'.','') from dbo.KL_KBK) 
		union
		select 'В справочнике КБК не найден КБК: ' + KBK_CODE_KT + '' as txt,1,1,0
		from #PROV_BKS
		where KBK_CODE_KT not in (select replace(CODE,'.','') from dbo.KL_KBK)
		order by txt
	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 @intKBK_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 @intKBK_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 EXECUTE ON dbo.[BK_IMPORT_PROV_FROM_BKS] TO PUBLIC

GO




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

GO

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

CREATE  PROCEDURE dbo.BK_REPORT_ACCUM_VED1
	@varKSdDate1	DATETIME	,
	@varKSdDate2	DATETIME	,
	@intACCOUNT	INT,
	@intKBK 	INT,
	@strCODE_AP	VARCHAR (60),
	@intSORT_CODE	INT,
	@intDepGroup	INT,
	@cVal1 CHAR (1), @nOtborLink1	INT, /* Отбор субсчетов */
	@cVal2 CHAR (1) = '', @nOtborLink2 INT = 0, /* Отбор субсчетов */
	@cVal_KAU CHAR (1) = '', @nOtborKAU  INT = 0,	/* Отбор КАУ */
	@intKAU_GRP INT =0	/* Выводить подитоги по КАУ */
AS
BEGIN

	DECLARE	@varKSDEP_LINK	INT,
		@varKSDIC_EMP	INT,
		@varKSORGNAME	VARCHAR(254),
		@strDATE_NEXT	VARCHAR (10),
		@strREP_NAME	VARCHAR (254),
		@intPRN_KBK	TINYINT,
		@MORE_ACCT	INT

	SELECT  @varKSDEP_LINK = LINK,
		@varKSORGNAME = dbo.BK_GET_PRINT_DEP_NAME (LINK)
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = COALESCE (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())

	SET @strDATE_NEXT = CONVERT (VARCHAR (10), DATEADD (DAY, 1, @varKSdDate2), 104)
	
	SET @intSORT_CODE = ISNULL (@intSORT_CODE, 0)
	SET @intKBK = ISNULL (@intKBK, 0)
	SET @intPRN_KBK = CASE 
				WHEN @intKBK = 0 THEN 0
				ELSE 1
			END

	SET @strCODE_AP = ISNULL (@strCODE_AP, '')

	IF @strCODE_AP <> 'DEP'
		SET @intDepGroup = 0

	--- Отбор субсчетов ---
	SET @intACCOUNT = ISNULL (@intACCOUNT, 0)
	DECLARE @ACCT_TABLE TABLE (LINK_ACCT INT)

	IF @intACCOUNT = 0	-- Счет не задан в параметрах отчета --
	BEGIN
		IF LEN (@cVal1) > 0	-- Задан фильтр отчета --
			INSERT INTO @ACCT_TABLE
			SELECT RECORD
			FROM OBJECT_VAR_ACCT
			WHERE LINK_UP = @nOtborLink1
		ELSE
			IF ISNULL (@strCODE_AP, '') = ''	-- Если показатель не указан, берем все счета --
				INSERT INTO @ACCT_TABLE
				SELECT T1.LINK
				FROM dbo.AccountsTableWithNoChild () T1
			ELSE					-- Выбор счетов, по которым настроен показатель --
				INSERT INTO @ACCT_TABLE
				SELECT T1.LINK
				FROM dbo.AccountsTableWithNoChild () T1
				INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = T1.LINK
				WHERE (@strCODE_AP = 'DEP' AND SA.AP_DEP = 1)
					OR (@strCODE_AP = 'EMP' AND SA.AP_EMP = 1)
					OR (@strCODE_AP = 'KAU' AND SA.AP_KAU = 1)
					OR (@strCODE_AP = 'AP2' AND SA.AP_AP2 = 1)
					OR (@strCODE_AP = 'EKR' AND SA.AP_EKR = 1)
					OR (@strCODE_AP = 'SUB' AND SA.AP_SUB = 1)
		SET @MORE_ACCT = 1
	END
	ELSE
	BEGIN
		INSERT INTO @ACCT_TABLE
		SELECT @intACCOUNT
		
		SET @MORE_ACCT = 0
	END

	--- Отбор организаций ---
	DECLARE @TAB_FIL TABLE (LINK_AP INT, AP_CODE VARCHAR (20),
		AP_NAME VARCHAR (254), GRP_NAME VARCHAR (254))
	IF @strCODE_AP = 'DEP' AND LEN (@cVal2) > 0	-- Задан фильтр отчета --
		INSERT INTO @TAB_FIL
		SELECT DEP.LINK,
			DEP.CODE,
			DEP.[NAME],
			DG.[NAME]
		FROM dbo.OBJECT_VAR_DEPARTMENT_GROUPS OVR
		INNER JOIN dbo.DEPARTMENT_GROUPS_REF DGR ON (DGR.GROUP_LINK = OVR.RECORD)
		INNER JOIN dbo.DEPARTMENT_GROUPS DG ON (DG.LINK = OVR.RECORD)
		INNER JOIN dbo.DEPARTMENTS DEP ON (DEP.LINK = DGR.DEP_LINK)
		WHERE OVR.LINK_UP = @nOtborLink2
	ELSE
		INSERT INTO @TAB_FIL
		SELECT LINK_AP,
			AP_CODE,
			AP_NAME,
			DG.[NAME]
		FROM dbo.BK_GetTableDictionByAP (@strCODE_AP) AP
		LEFT JOIN dbo.DEPARTMENT_GROUPS_REF DGR ON (DGR.DEP_LINK = AP.LINK_AP
			AND @strCODE_AP = 'DEP'
			AND @intDepGroup = 1)
		LEFT JOIN dbo.DEPARTMENT_GROUPS DG ON (DG.LINK = DGR.GROUP_LINK)

	DECLARE @TABLE_KAU TABLE (KAU INT, KAU_CODE VARCHAR (20))
	IF @intKAU_GRP = 1 OR @strCODE_AP = 'KAU'
		IF LEN (@cVal_KAU) > 0
			INSERT INTO @TABLE_KAU
			SELECT OVR.RECORD,
				KAU.CODE
			FROM dbo.OBJECT_VAR_KAU OVR
			INNER JOIN dbo.KAU ON (KAU.LINK = OVR.RECORD)
			WHERE OVR.LINK_UP = @nOtborKAU
		ELSE
			INSERT INTO @TABLE_KAU
			SELECT LINK_AP,
				AP_CODE
			FROM dbo.BK_GetTableDictionByAP ('KAU')
	ELSE
		INSERT INTO @TABLE_KAU
		SELECT 0, ''

	DECLARE @TABLE1 TABLE (ACCOUNT [INT], AP [INT], KBK [INT], 
			KAU 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 @strCODE_AP = 'DEP' THEN T1.DEP
			WHEN @strCODE_AP = 'EMP' THEN T1.EMP
			WHEN @strCODE_AP = 'KAU' THEN T1.KAU
			WHEN @strCODE_AP = 'AP2' THEN T1.AP2	-- ДОП. КЛАСС.
			WHEN @strCODE_AP = 'EKR' THEN T1.EKR	-- 
			WHEN @strCODE_AP = 'SUB' THEN T1.SUB	-- 
			ELSE 0
		END,
		CASE 
			WHEN @intKBK = 0 THEN 0 
			ELSE T1.KBK
		END,
		CASE 
			WHEN @intKAU_GRP = 1 OR @strCODE_AP = 'KAU' THEN T1.KAU
			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_TABLE AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	WHERE @intKBK = 0
		OR (@intKBK <> 0 AND T1.KBK = @intKBK)
	GROUP BY T1.ACCOUNT,
		CASE 
			WHEN @strCODE_AP = 'DEP' THEN T1.DEP
			WHEN @strCODE_AP = 'EMP' THEN T1.EMP
			WHEN @strCODE_AP = 'KAU' THEN T1.KAU
			WHEN @strCODE_AP = 'AP2' THEN T1.AP2	-- ДОП. КЛАСС.
			WHEN @strCODE_AP = 'EKR' THEN T1.EKR	-- 
			WHEN @strCODE_AP = 'SUB' THEN T1.SUB	-- 
			ELSE 0
		END,
		CASE 
			WHEN @intKBK = 0 THEN 0 
			ELSE T1.KBK
		END,
		CASE 
			WHEN @intKAU_GRP = 1 OR @strCODE_AP = 'KAU' THEN T1.KAU
			ELSE 0
		END

	DECLARE @RESULT TABLE  (ACCOUNT [INT], AP [INT], KBK [INT],
			ACCT_GR VARCHAR (30), ACCT_CODE VARCHAR (60), 
			AP_CODE [VARCHAR] (20), AP_NAME [VARCHAR] (254),
			KBK_CODE [VARCHAR] (30), KAU INT, KAU_CODE VARCHAR (20),
			D_SUM [NUMERIC] (20,2),	K_SUM [NUMERIC] (20,2), 
			IN_SUM [NUMERIC] (20,2), OUT_SUM [NUMERIC] (20,2),
			ORGNAME [VARCHAR] (254), DATE_NEXT VARCHAR (10), DEP_GROUP varchar (100),
			AP_TYPE VARCHAR (60))

	INSERT INTO @RESULT
	SELECT OSV.ACCOUNT,
		OSV.AP,
		OSV.KBK,
		SA.CODE,
		dbo.BK_GetAcctFullCode1 (OSV.ACCOUNT, OSV.KBK, DEFAULT, @intPRN_KBK, 0),
		T_AP.AP_CODE,
		T_AP.AP_NAME,
		ISNULL (KL_KBK.CODE, ''),
		KAU.KAU,
		KAU.KAU_CODE,
		OSV.D_SUMMA, 
		OSV.K_SUMMA, 
		OSV.IN_SUMMA, 
		OSV.OUT_SUMMA,
		@varKSORGNAME,
		@strDATE_NEXT,
		ISNULL(T_AP.GRP_NAME,''),
		@strCODE_AP
	FROM @TABLE1 OSV
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.ACCOUNT)
	INNER JOIN @TABLE_KAU KAU ON (KAU.KAU = OSV.KAU)
	LEFT JOIN @TAB_FIL T_AP ON (T_AP.LINK_AP = OSV.AP)
	LEFT OUTER JOIN dbo.KL_KBK ON (KL_KBK.LINK = OSV.KBK)
	WHERE (@intDepGroup = 0
		OR @intDepGroup > 0
			AND @strCODE_AP = 'DEP'
			AND T_AP.LINK_AP = OSV.AP)
		AND ((OSV.D_SUMMA <> 0)
		OR (OSV.K_SUMMA <> 0) 
		OR (OSV.IN_SUMMA <> 0)
		OR (OSV.OUT_SUMMA <> 0))


	IF @intSORT_CODE = 0
		SELECT *,
			@MORE_ACCT AS MORE_ACCT
		FROM @RESULT
			ORDER BY ACCT_GR, KAU_CODE, DEP_GROUP, AP_NAME 
	ELSE
		SELECT *,
			@MORE_ACCT AS MORE_ACCT
		FROM @RESULT
			ORDER BY ACCT_GR, KAU_CODE, DEP_GROUP,RIGHT ('00000000000000000000' + AP_CODE, 20)


END


GO


GRANT EXECUTE ON dbo.[BK_REPORT_ACCUM_VED1] TO PUBLIC

GO



GO

--AFTER CODE 08.02.2016
-- 3. Добавление новых счетов --

IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR WHERE SINTH = '501' AND [ANALITH] = '93')
	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 'Лимиты бюджетных обязательств получателей бюджетных средств', '501', '93', 1, 0, 0, 0, 0, 'КРБ, КИФ', 1, '', 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, '09', 0, 0, 0, 0

IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR WHERE SINTH = '502' AND [ANALITH] = '99')
	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 'Отложенные обязательства', '502', '99', 7, 0, 0, 0, 0, 'КРБ, КИФ', 1, '', 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, '09', 0, 0, 0, 0

IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR WHERE SINTH = '506' AND [ANALITH] = '90')
	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 'Право на принятие обязательств', '506', '90', 6, 0, 0, 0, 0, 'КРБ, КИФ', 1, '', 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, '09', 0, 0, 0, 0
GO
-- Загрузка изменений ПС --

IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW = '501' AND [ANALITH_NEW] = '93' AND [BUF_NAME] = '#UNLOAD_SA_501_2016-02-01 15:52:13')
	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, '', '', '501', '93', 'Лимиты бюджетных обязательств получателей бюджетных средств', 0 , '#UNLOAD_SA_501_2016-02-01 15:52:13', 3, 0, USER_SID ()

IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW = '502' AND [ANALITH_NEW] = '99' AND [BUF_NAME] = '#UNLOAD_SA_501_2016-02-01 15:52:13')
	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', '99', 'Отложенные обязательства', 0 , '#UNLOAD_SA_501_2016-02-01 15:52:13', 3, 0, USER_SID ()

IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW = '506' AND [ANALITH_NEW] = '90' AND [BUF_NAME] = '#UNLOAD_SA_501_2016-02-01 15:52:13')
	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', '90', 'Право на принятие обязательств', 0 , '#UNLOAD_SA_501_2016-02-01 15:52:13', 3, 0, USER_SID ()
GO
-- Загрузка S_ACCOUNTS_NASTR_KOSGU --
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '501' AND ANALITH = '93' AND SGU = '200')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '501' AND ANALITH = '93' AND SGU = '200'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('501', '93', '200', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '501' AND ANALITH = '93' AND SGU = '211')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '501' AND ANALITH = '93' AND SGU = '211'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('501', '93', '211', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '501' AND ANALITH = '93' AND SGU = '213')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '501' AND ANALITH = '93' AND SGU = '213'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('501', '93', '213', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '501' AND ANALITH = '93' AND SGU = '225')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '501' AND ANALITH = '93' AND SGU = '225'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('501', '93', '225', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '501' AND ANALITH = '93' AND SGU = '226')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '501' AND ANALITH = '93' AND SGU = '226'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('501', '93', '226', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '501' AND ANALITH = '93' AND SGU = '290')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '501' AND ANALITH = '93' AND SGU = '290'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('501', '93', '290', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '502' AND ANALITH = '99' AND SGU = '200')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '502' AND ANALITH = '99' AND SGU = '200'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('502', '99', '200', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '502' AND ANALITH = '99' AND SGU = '211')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '502' AND ANALITH = '99' AND SGU = '211'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('502', '99', '211', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '502' AND ANALITH = '99' AND SGU = '213')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '502' AND ANALITH = '99' AND SGU = '213'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('502', '99', '213', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '502' AND ANALITH = '99' AND SGU = '225')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '502' AND ANALITH = '99' AND SGU = '225'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('502', '99', '225', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '502' AND ANALITH = '99' AND SGU = '226')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '502' AND ANALITH = '99' AND SGU = '226'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('502', '99', '226', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '502' AND ANALITH = '99' AND SGU = '290')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '502' AND ANALITH = '99' AND SGU = '290'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('502', '99', '290', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '506' AND ANALITH = '90' AND SGU = '200')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '506' AND ANALITH = '90' AND SGU = '200'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('506', '90', '200', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '506' AND ANALITH = '90' AND SGU = '211')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '506' AND ANALITH = '90' AND SGU = '211'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('506', '90', '211', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '506' AND ANALITH = '90' AND SGU = '213')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '506' AND ANALITH = '90' AND SGU = '213'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('506', '90', '213', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '506' AND ANALITH = '90' AND SGU = '225')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '506' AND ANALITH = '90' AND SGU = '225'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('506', '90', '225', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '506' AND ANALITH = '90' AND SGU = '226')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '506' AND ANALITH = '90' AND SGU = '226'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('506', '90', '226', '', 0)
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '506' AND ANALITH = '90' AND SGU = '290')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU SET NAME = '', DB_KR = 0	WHERE SINTH = '506' AND ANALITH = '90' AND SGU = '290'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )	VALUES ('506', '90', '290', '', 0)
GO
-- Измение плана счетов --
DECLARE
	@BUF_NAME	VARCHAR (254)

SET @BUF_NAME = '#UNLOAD_SA_501_2016-02-01 15:52:13'

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
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXBD160101' AND CODE = 'BD'
IF @varKSModelLink is null
begin
	INSERT INTO EXPORT_MODELS(CODE, NAME, MODEL_VER, ISONCE, NORM_DOC, FILE_NAME_MASK, FILE_NAME_PROC, PROC_EXP, PROC_DOP_PARAM, DEP_NAME, PROG_SAVE, DATE_END)
	SELECT 'BD','Информация из расчетных документов','TXBD160101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_PP','cModelVer','KOD_UBP','bb_import_BD()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Информация из расчетных документов',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_PP',
		PROC_DOP_PARAM   = 'cModelVer',
		PROG_SAVE   = 'bb_import_BD()',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,0,0,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,0,0,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,0,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NAME_UBP','Наименование УБП','STRING',254,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BD'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BD',4,0,'Общая информация',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 0,
			NAME   = 'Общая информация',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер лицевого счета клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'LS','Номер лицевого счета клиента','STRING',11,0,0,0,'LS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Дата',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'DATE','Дата','DATE',0,0,0,0,'DATE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_OTCH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'GUID_OTCH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_OTCH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'GUID_OTCH','Глобальный уникальный идентификатор','GUID',36,1,0,1,'GUID_OTCH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KOD_DOC','Код документа','STRING',2,1,1,1,'KOD_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OTCH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Признак принад-лежности к про-межуточному отчёту',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_OTCH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OTCH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'VID_OTCH','Признак принад-лежности к про-межуточному отчёту','STRING',1,1,1,1,'VID_OTCH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Количество документов',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'KOL','Количество документов','NUMBER',5,1,1,1,'KOL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_TOTAL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Контрольная сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_TOTAL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_TOTAL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'SUM_TOTAL','Контрольная сумма','NUMBER2',0,0,1,1,'SUM_TOTAL','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BDPD'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BDPD',5,2,'Информация из расчетных до-кументов',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Информация из расчетных до-кументов',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= '№ платежного поручения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NOM_PP','№ платежного поручения','STRING',10,0,1,1,'NOM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Дата платежного поручения',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'DATE_PP','Дата платежного поручения','DATE',0,1,1,1,'DATE_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Сумма платежного поручения',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'SUM_PP','Сумма платежного поручения','NUMBER2',0,1,1,1,'SUM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Вид платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'VID_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'VID_PL','Вид платежа','STRING',1,1,0,0,'VID_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_IN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Поступило в банк платель-щика.',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PP_IN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_IN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'DATE_PP_IN','Поступило в банк платель-щика.','DATE',0,0,0,0,'DATE_PP_IN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_SPS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Дата списания со счета плательщика.',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PP_SPS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_SPS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'DATE_PP_SPS','Дата списания со счета плательщика.','DATE',0,0,0,0,'DATE_PP_SPS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Вид операции.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'VID_OPER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'VID_OPER','Вид операции.','STRING',2,1,0,0,'VID_OPER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'ИНН Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'INN_PAY','ИНН Плательщика','STRING',12,0,0,0,'INN_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'КПП Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'KPP_PAY','КПП Плательщика','STRING',9,1,0,0,'KPP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Наименование Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'CNAME_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'CNAME_PAY','Наименование Плательщика','STRING',160,0,0,0,'CNAME_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Расчетный счет Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'BS_PAY','Расчетный счет Плательщика','STRING',20,1,0,0,'BS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'БИК банка Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BIC_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'BIC_PAY','БИК банка Плательщика','STRING',9,1,0,0,'BIC_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Наименование банка Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BIC_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'NAME_BIC_PAY','Наименование банка Плательщика','STRING',160,0,0,0,'NAME_BIC_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Коррсчет банка Плательщика в РКЦ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_KS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'BS_KS_PAY','Коррсчет банка Плательщика в РКЦ','STRING',20,1,0,0,'BS_KS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'ИНН получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'INN_RCP','ИНН получателя','STRING',12,0,0,0,'INN_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'КПП получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'KPP_RCP','КПП получателя','STRING',9,0,0,0,'KPP_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'NAME_RCP','Наименование получателя','STRING',160,0,0,0,'NAME_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Расчетный счет Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'BS_RCP','Расчетный счет Получателя','STRING',20,0,0,0,'BS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'БИК банка Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'BIC_RCP','БИК банка Получателя','STRING',9,1,0,0,'BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Наименование банка получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'NAME_BIC_RCP','Наименование банка получателя','STRING',160,0,0,0,'NAME_BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Корсчет банка получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_KS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 22,'BS_KS_RCP','Корсчет банка получателя','STRING',20,1,0,0,'BS_KS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Срок платежа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 23,'DATE_PAY','Срок платежа','DATE',0,0,0,0,'DATE_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Очередность платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ORDER_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 24,'ORDER_PAY','Очередность платежа','STRING',1,1,0,0,'ORDER_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'UIN_CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Уникальный идентификатор начисления (Код)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 25,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'UIN_CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'UIN_CODE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 25,'UIN_CODE','Уникальный идентификатор начисления (Код)','STRING',25,0,0,0,'UIN_CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 26,'PURPOSE','Назначение платежа','STRING',210,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Статус составителя расчетного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PAYSTATUS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 27,'PAYSTATUS','Статус составителя расчетного документа','STRING',2,0,0,0,'PAYSTATUS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Код бюджетной классификации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'KBK','Код бюджетной классификации','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Код ОКТМО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKATO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 29,'OKATO','Код ОКТМО','STRING',11,0,0,0,'OKATO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNPLAT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Показатель основания платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OSNPLAT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNPLAT'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 30,'OSNPLAT','Показатель основания платежа','STRING',2,0,0,0,'OSNPLAT','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'Показатель налогового периода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAL_PER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 31,'NAL_PER','Показатель налогового периода','STRING',10,0,0,0,'NAL_PER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Показатель номера документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'NOM_DOK','Показатель номера документа','STRING',15,0,0,0,'NOM_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Показатель даты документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 33,'DATE_DOK','Показатель даты документа','STRING',10,0,0,0,'DATE_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 34,
		NAME   		= 'Тип платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 34,'TYPE_PL','Тип платежа','STRING',2,0,0,0,'TYPE_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PL_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 35,
		NAME   		= 'Номер частичного платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_PL_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PL_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 35,'NOM_PL_PO','Номер частичного платежа','STRING',3,0,0,0,'NOM_PL_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SHIFR_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 36,
		NAME   		= 'Шифр платежно-го документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SHIFR_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SHIFR_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 36,'SHIFR_RD_PO','Шифр платежно-го документа','STRING',2,1,0,0,'SHIFR_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 37,
		NAME   		= 'Номер платежного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 37,'NOM_RD_PO','Номер платежного документа','STRING',3,0,0,0,'NOM_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 38,
		NAME   		= 'Дата платежного документа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 38,'DATE_RD_PO','Дата платежного документа','DATE',0,0,0,0,'DATE_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OST_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 39,
		NAME   		= 'Сумма остатка платежа',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_OST_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OST_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 39,'SUM_OST_PO','Сумма остатка платежа','NUMBER2',0,0,0,0,'SUM_OST_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OPER_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 40,
		NAME   		= 'Содержание опе-рации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OPER_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OPER_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 40,'OPER_PO','Содержание опе-рации','STRING',16,0,0,0,'OPER_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_IN_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 41,
		NAME   		= 'Дата выписки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_IN_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_IN_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 41,'DATE_IN_TOFK','Дата выписки','DATE',0,0,0,0,'DATE_IN_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 42,
		NAME   		= 'Глобальный уни-кальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 42,'GUID','Глобальный уни-кальный идентификатор','GUID',36,1,0,0,'GUID','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BDPDST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BDPDST',6,2,'Строки платежного поручения по бюджетной классификации',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Строки платежного поручения по бюджетной классификации',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KBK','Код по КБК','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'TYPE_KBK','Тип КБК','STRING',2,1,0,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код цели субсидии',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'ADD_KLASS','Код цели субсидии','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Номер бюджетного обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 19,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NUM_BO','Номер бюджетного обязательства','STRING',19,1,0,0,'NUM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ОКАТО')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'ОКТMО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ОКАТО',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ОКАТО'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'ОКАТО','ОКТMО','STRING',11,1,0,0,'ОКАТО','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'SUM','Сумма','NUMBER2',0,1,1,1,'SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Направление пла-тежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DIR_SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'DIR_SUM','Направление пла-тежа','STRING',1,1,1,1,'DIR_SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Месяц финансиро-вания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'MES_FIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'MES_FIN','Месяц финансиро-вания','STRING',2,1,0,0,'MES_FIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Резервное поле',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 40,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'REZERV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'REZERV','Резервное поле','STRING',40,0,0,0,'REZERV','',''
GO

GO
update EXPORT_MODELS set DATE_END   = '20150331' 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_br16()',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_br16()',
		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 = 'IST')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		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, 13,'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 		= 14,
		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, 14,'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 		= 15,
		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, 15,'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 		= 16,
		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, 16,'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 		= 17,
		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, 17,'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 		= 18,
		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, 18,'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 		= 19,
		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, 19,'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 		= 20,
		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, 20,'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 		= 21,
		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, 21,'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 		= 22,
		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, 22,'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 		= 23,
		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, 23,'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 		= 24,
		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, 24,'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 		= 25,
		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, 25,'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 		= 26,
		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, 26,'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 		= 27,
		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, 27,'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 		= 28,
		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, 28,'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 = '2011.01' AND CODE = 'ZF'
GO
update EXPORT_MODELS set DATE_END   = '20150331' WHERE MODEL_VER = '2009.01' AND CODE = 'ZF'
GO
update EXPORT_MODELS set DATE_END   = '20150331' WHERE MODEL_VER = '2011.01' AND CODE = 'IP'
GO
update EXPORT_MODELS set DATE_END   = '20150331' WHERE MODEL_VER = '2009.01' AND CODE = 'IP'
GO
update EXPORT_MODELS set DATE_END   = '20150331' WHERE MODEL_VER = '2011.01' AND CODE = 'EP'
GO
update EXPORT_MODELS set DATE_END   = '20150331' WHERE MODEL_VER = '2009.01' AND CODE = 'EP'
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = '2013.08' AND CODE = 'EP'
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 'EP','Кассовый план расходы','2013.08',0,'','XXXXXDNN.TTM','fb_file_name_doc','FB_EXPORT_KP','cObjCode'',''&cModelVer','KOD_BP','',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_KP',
		PROC_DOP_PARAM   = 'cObjCode'',''&cModelVer',
		PROG_SAVE   = '',
		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	= 0,
		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,0,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	= 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, 1,'KOD_BP','Код бюджетополучателя','STRING',5,0,0,1,'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	= 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, 2,'NAME_BP','Наименование бюджетополучателя','STRING',512,0,0,1,'NAME_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_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ФО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_FO','Код ФО','STRING',5,0,0,1,'KOD_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ФО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_FO','Наименование ФО','STRING',512,0,0,1,'NAME_FO','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'KP'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'KP',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 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID','Уникальный идентификатор документа','GUID',0,0,0,0,'GUID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUMBER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= '№ заявки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		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, 2,'NUMBER','№ заявки','STRING',15,0,0,1,'NUMBER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Дата',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE',
		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, 3,'DATE','Дата','DATE',NULL,0,1,1,'DATE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_EXEC')
	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_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, 4,'DATE_EXEC','Дата вступления в силу','DATE',NULL,0,0,0,'DATE_EXEC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_BEGIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Дата начала периода',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_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, 5,'DATE_BEGIN','Дата начала периода','DATE',0,0,0,0,'DATE_BEGIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PERIOD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		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, 6,'PERIOD','Период ведения документа','STRING',1,1,1,1,'PERIOD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACCOUNT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Счет отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ACCOUNT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACCOUNT'
else		
	INSERT INTO EXPORT_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,'ACCOUNT','Счет отправителя','STRING',20,0,0,0,'ACCOUNT','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Сумма заявки',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUMMA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA'
else		
	INSERT INTO EXPORT_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,'SUMMA','Сумма заявки','NUMBER2',NULL,0,0,1,'SUMMA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ANALITICS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		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, 9,'ANALITICS','Аналитические признаки','STRING',250,0,0,0,'ANALITICS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BUD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'NAME_BUD','Наименование бюджета','STRING',512,0,1,1,'NAME_BUD','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'KPST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'KPST',5,2,'Строки заявки',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Строки заявки',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код по ППП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GLAVA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA'
else		
	INSERT INTO EXPORT_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,'GLAVA','Код по ППП','STRING',3,1,1,0,'GLAVA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'RAZDEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код по ФКР',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'RAZDEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'RAZDEL'
else		
	INSERT INTO EXPORT_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,'RAZDEL','Код по ФКР','STRING',4,1,1,0,'RAZDEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'STATIA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код по КЦСР',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 7,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'STATIA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'STATIA'
else		
	INSERT INTO EXPORT_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,'STATIA','Код по КЦСР','STRING',7,1,0,0,'STATIA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код по КВР',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		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, 4,'VID','Код по КВР','STRING',3,1,0,0,'VID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'E_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Код по ЭКР',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'E_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'E_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, 5,'E_KLASS','Код по ЭКР','STRING',3,1,0,0,'E_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KKIVNF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Код КИВнФ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KKIVNF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KKIVNF'
else		
	INSERT INTO EXPORT_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,'KKIVNF','Код КИВнФ','STRING',20,1,0,0,'KKIVNF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KKIVF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Код КИВФ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KKIVF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KKIVF'
else		
	INSERT INTO EXPORT_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,'KKIVF','Код КИВФ','STRING',20,1,0,0,'KKIVF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KDOH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Код дохода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KDOH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KDOH'
else		
	INSERT INTO EXPORT_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,'KDOH','Код дохода','STRING',20,1,0,0,'KDOH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Доп. Классификация',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'ADD_KLASS','Доп. Классификация','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LOCAL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		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, 10,'LOCAL','Региональная классификация','STRING',20,0,0,0,'LOCAL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Сумма по классификации',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUMMA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA'
else		
	INSERT INTO EXPORT_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,'SUMMA','Сумма по классификации','NUMBER2',0,0,0,1,'SUMMA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA1')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Сумма за 1-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA1',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA1'
else		
	INSERT INTO EXPORT_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,'SUMMA1','Сумма за 1-й интервал периода','NUMBER2',0,0,0,0,'SUMMA1','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA2')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Сумма за 2-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA2',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA2'
else		
	INSERT INTO EXPORT_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,'SUMMA2','Сумма за 2-й интервал периода','NUMBER2',0,0,0,0,'SUMMA2','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA3')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Сумма за 3-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA3',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA3'
else		
	INSERT INTO EXPORT_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,'SUMMA3','Сумма за 3-й интервал периода','NUMBER2',0,0,0,0,'SUMMA3','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA4')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Сумма за 4-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA4',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA4'
else		
	INSERT INTO EXPORT_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,'SUMMA4','Сумма за 4-й интервал периода','NUMBER2',0,0,0,0,'SUMMA4','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA5')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Сумма за 5-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA5',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA5'
else		
	INSERT INTO EXPORT_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,'SUMMA5','Сумма за 5-й интервал периода','NUMBER2',0,0,0,0,'SUMMA5','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA6')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Сумма за 6-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA6',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA6'
else		
	INSERT INTO EXPORT_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,'SUMMA6','Сумма за 6-й интервал периода','NUMBER2',0,0,0,0,'SUMMA6','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA7')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Сумма за 7-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA7',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA7'
else		
	INSERT INTO EXPORT_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,'SUMMA7','Сумма за 7-й интервал периода','NUMBER2',0,0,0,0,'SUMMA7','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA8')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Сумма за 8-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA8',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA8'
else		
	INSERT INTO EXPORT_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,'SUMMA8','Сумма за 8-й интервал периода','NUMBER2',0,0,0,0,'SUMMA8','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA9')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Сумма за 9-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA9',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA9'
else		
	INSERT INTO EXPORT_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,'SUMMA9','Сумма за 9-й интервал периода','NUMBER2',0,0,0,0,'SUMMA9','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA10')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Сумма за 10-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA10',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA10'
else		
	INSERT INTO EXPORT_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,'SUMMA10','Сумма за 10-й интервал периода','NUMBER2',0,0,0,0,'SUMMA10','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA11')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Сумма за 11-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA11',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA11'
else		
	INSERT INTO EXPORT_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,'SUMMA11','Сумма за 11-й интервал периода','NUMBER2',0,0,0,0,'SUMMA11','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA12')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Сумма за 12-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA12',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA12'
else		
	INSERT INTO EXPORT_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,'SUMMA12','Сумма за 12-й интервал периода','NUMBER2',0,0,0,0,'SUMMA12','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM_STR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Примечание к строке',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 255,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PRIM_STR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM_STR'
else		
	INSERT INTO EXPORT_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,'PRIM_STR','Примечание к строке','STRING',255,0,0,0,'PRIM_STR','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = '2013.08' AND CODE = 'IP'
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 'IP','Кассовый план доходы','2013.08',0,'','XXXXXDNN.TTM','fb_file_name_doc','FB_EXPORT_KP','cObjCode'',''&cModelVer','KOD_BP','',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_KP',
		PROC_DOP_PARAM   = 'cObjCode'',''&cModelVer',
		PROG_SAVE   = '',
		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	= 0,
		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,0,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	= 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, 1,'KOD_BP','Код бюджетополучателя','STRING',5,0,0,1,'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	= 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, 2,'NAME_BP','Наименование бюджетополучателя','STRING',512,0,0,1,'NAME_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_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ФО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_FO','Код ФО','STRING',5,0,0,1,'KOD_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ФО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_FO','Наименование ФО','STRING',512,0,0,1,'NAME_FO','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'KP'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'KP',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 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID','Уникальный идентификатор документа','GUID',0,0,0,0,'GUID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUMBER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= '№ заявки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		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, 2,'NUMBER','№ заявки','STRING',15,0,0,1,'NUMBER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Дата',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE',
		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, 3,'DATE','Дата','DATE',NULL,0,1,1,'DATE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_EXEC')
	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_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, 4,'DATE_EXEC','Дата вступления в силу','DATE',NULL,0,0,0,'DATE_EXEC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_BEGIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Дата начала периода',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_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, 5,'DATE_BEGIN','Дата начала периода','DATE',0,0,0,0,'DATE_BEGIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PERIOD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		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, 6,'PERIOD','Период ведения документа','STRING',1,1,1,1,'PERIOD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACCOUNT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Счет отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ACCOUNT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACCOUNT'
else		
	INSERT INTO EXPORT_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,'ACCOUNT','Счет отправителя','STRING',20,0,0,0,'ACCOUNT','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Сумма заявки',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUMMA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA'
else		
	INSERT INTO EXPORT_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,'SUMMA','Сумма заявки','NUMBER2',NULL,0,0,1,'SUMMA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ANALITICS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		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, 9,'ANALITICS','Аналитические признаки','STRING',250,0,0,0,'ANALITICS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BUD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'NAME_BUD','Наименование бюджета','STRING',512,0,1,1,'NAME_BUD','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'KPST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'KPST',5,2,'Строки заявки',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Строки заявки',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код по ППП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GLAVA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA'
else		
	INSERT INTO EXPORT_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,'GLAVA','Код по ППП','STRING',3,1,1,0,'GLAVA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'RAZDEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код по ФКР',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'RAZDEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'RAZDEL'
else		
	INSERT INTO EXPORT_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,'RAZDEL','Код по ФКР','STRING',4,1,1,0,'RAZDEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'STATIA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код по КЦСР',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 7,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'STATIA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'STATIA'
else		
	INSERT INTO EXPORT_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,'STATIA','Код по КЦСР','STRING',7,1,0,0,'STATIA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код по КВР',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		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, 4,'VID','Код по КВР','STRING',3,1,0,0,'VID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'E_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Код по ЭКР',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'E_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'E_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, 5,'E_KLASS','Код по ЭКР','STRING',3,1,0,0,'E_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KKIVNF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Код КИВнФ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KKIVNF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KKIVNF'
else		
	INSERT INTO EXPORT_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,'KKIVNF','Код КИВнФ','STRING',20,1,0,0,'KKIVNF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KKIVF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Код КИВФ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KKIVF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KKIVF'
else		
	INSERT INTO EXPORT_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,'KKIVF','Код КИВФ','STRING',20,1,0,0,'KKIVF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KDOH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Код дохода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KDOH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KDOH'
else		
	INSERT INTO EXPORT_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,'KDOH','Код дохода','STRING',20,1,0,0,'KDOH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Доп. Классификация',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'ADD_KLASS','Доп. Классификация','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LOCAL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		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, 10,'LOCAL','Региональная классификация','STRING',20,0,0,0,'LOCAL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Сумма по классификации',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUMMA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA'
else		
	INSERT INTO EXPORT_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,'SUMMA','Сумма по классификации','NUMBER2',0,0,0,1,'SUMMA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA1')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Сумма за 1-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA1',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA1'
else		
	INSERT INTO EXPORT_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,'SUMMA1','Сумма за 1-й интервал периода','NUMBER2',0,0,0,0,'SUMMA1','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA2')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Сумма за 2-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA2',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA2'
else		
	INSERT INTO EXPORT_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,'SUMMA2','Сумма за 2-й интервал периода','NUMBER2',0,0,0,0,'SUMMA2','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA3')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Сумма за 3-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA3',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA3'
else		
	INSERT INTO EXPORT_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,'SUMMA3','Сумма за 3-й интервал периода','NUMBER2',0,0,0,0,'SUMMA3','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA4')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Сумма за 4-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA4',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA4'
else		
	INSERT INTO EXPORT_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,'SUMMA4','Сумма за 4-й интервал периода','NUMBER2',0,0,0,0,'SUMMA4','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA5')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Сумма за 5-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA5',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA5'
else		
	INSERT INTO EXPORT_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,'SUMMA5','Сумма за 5-й интервал периода','NUMBER2',0,0,0,0,'SUMMA5','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA6')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Сумма за 6-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA6',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA6'
else		
	INSERT INTO EXPORT_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,'SUMMA6','Сумма за 6-й интервал периода','NUMBER2',0,0,0,0,'SUMMA6','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA7')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Сумма за 7-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA7',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA7'
else		
	INSERT INTO EXPORT_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,'SUMMA7','Сумма за 7-й интервал периода','NUMBER2',0,0,0,0,'SUMMA7','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA8')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Сумма за 8-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA8',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA8'
else		
	INSERT INTO EXPORT_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,'SUMMA8','Сумма за 8-й интервал периода','NUMBER2',0,0,0,0,'SUMMA8','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA9')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Сумма за 9-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA9',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA9'
else		
	INSERT INTO EXPORT_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,'SUMMA9','Сумма за 9-й интервал периода','NUMBER2',0,0,0,0,'SUMMA9','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA10')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Сумма за 10-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA10',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA10'
else		
	INSERT INTO EXPORT_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,'SUMMA10','Сумма за 10-й интервал периода','NUMBER2',0,0,0,0,'SUMMA10','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA11')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Сумма за 11-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA11',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA11'
else		
	INSERT INTO EXPORT_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,'SUMMA11','Сумма за 11-й интервал периода','NUMBER2',0,0,0,0,'SUMMA11','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA12')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Сумма за 12-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA12',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA12'
else		
	INSERT INTO EXPORT_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,'SUMMA12','Сумма за 12-й интервал периода','NUMBER2',0,0,0,0,'SUMMA12','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM_STR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Примечание к строке',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 255,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PRIM_STR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM_STR'
else		
	INSERT INTO EXPORT_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,'PRIM_STR','Примечание к строке','STRING',255,0,0,0,'PRIM_STR','',''
GO

GO
update EXPORT_MODELS set DATE_END   = '20150331' 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_br16()',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_br16()',
		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 = 'IST')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		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, 13,'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 		= 14,
		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, 14,'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 		= 15,
		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, 15,'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 		= 16,
		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, 16,'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 		= 17,
		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, 17,'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 		= 18,
		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, 18,'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 		= 19,
		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, 19,'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 		= 20,
		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, 20,'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 		= 21,
		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, 21,'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 		= 22,
		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, 22,'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 		= 23,
		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, 23,'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 		= 24,
		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, 24,'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 		= 25,
		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, 25,'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 		= 26,
		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, 26,'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 		= 27,
		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, 27,'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 		= 28,
		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, 28,'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   = '20151231' where MODEL_VER = 'TXUF120101' AND CODE = 'UF'
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXUF140101' AND CODE = 'UF'
IF @varKSModelLink is null
begin
	INSERT INTO EXPORT_MODELS(CODE, NAME, MODEL_VER, ISONCE, NORM_DOC, FILE_NAME_MASK, FILE_NAME_PROC, PROC_EXP, PROC_DOP_PARAM, DEP_NAME, PROG_SAVE, DATE_END)
	SELECT 'UF','Уведомление об уточнении вида и принадлежности платежа','TXUF140101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_UF_16','','KOD_UBP','',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Уведомление об уточнении вида и принадлежности платежа',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_UF_16',
		PROC_DOP_PARAM   = '',
		PROG_SAVE   = '',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Ссылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','Ссылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,1,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NAME_UBP','Наименование УБП','STRING',2000,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'UF'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'UF',4,2,'Уведомление об уточнении вида и принадлежности платежа',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Уведомление об уточнении вида и принадлежности платежа',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID_FK','Глобальный уникальный идентификатор','STRING',36,0,0,0,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_UF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Номер Уведомления',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_UF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_UF'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NOM_UF','Номер Уведомления','STRING',15,0,1,1,'NOM_UF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Дата Уведомления',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_UF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UF'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'DATE_UF','Дата Уведомления','DATE',NULL,0,1,1,'DATE_UF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Наименование ПБС/АДБ/АИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NAME_UBP','Наименование ПБС/АДБ/АИФДБ','STRING',2000,0,0,0,'NAME_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Код по Сводному реестру ПБС/АДБ/АИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'KOD_UBP','Код по Сводному реестру ПБС/АДБ/АИФДБ','STRING',5,0,0,0,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Номер лицевого счета ПБС/АДБ/АИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'LS_UBP','Номер лицевого счета ПБС/АДБ/АИФДБ','STRING',11,1,1,0,'LS_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_GRS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Наименование ГРБС/ГАДБ/ГАИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_GRS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_GRS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'NAME_GRS','Наименование ГРБС/ГАДБ/ГАИФДБ','STRING',2000,0,0,0,'NAME_GRS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Глава по БК ГРБС/ГАДБ/ГАИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GLAVA_GRS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'GLAVA_GRS','Глава по БК ГРБС/ГАДБ/ГАИФДБ','STRING',3,1,1,0,'GLAVA_GRS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BUD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'NAME_BUD','Наименование бюджета','STRING',512,0,1,1,'NAME_BUD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Наименование финансового органа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'NAME_UBP_FO','Наименование финансового органа','STRING',2000,0,0,0,'NAME_UBP_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Лицевой счет финансового органа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'LS_FO','Лицевой счет финансового органа','STRING',11,1,0,0,'LS_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Наименование органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'NAME_TOFK','Наименование органа ФК','STRING',2000,0,0,1,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Код органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'KOD_TOFK','Код органа ФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FUND_SOURCE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Вид средств',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'FUND_SOURCE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FUND_SOURCE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'FUND_SOURCE','Вид средств','STRING',1,1,0,0,'FUND_SOURCE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Номер запроса ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_ZF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZF'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'NOM_ZF','Номер запроса ОрФК','STRING',15,0,0,0,'NOM_ZF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Дата запроса',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_ZF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZF'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'DATE_ZF','Дата запроса','DATE',NULL,0,0,0,'DATE_ZF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'СNAME_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Наименование плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'СNAME_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'СNAME_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'СNAME_PL','Наименование плательщика','STRING',160,0,0,0,'СNAME_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'ИНН плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'INN_PL','ИНН плательщика','STRING',12,0,0,0,'INN_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'КПП плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'KPP_PL','КПП плательщика','STRING',9,0,0,0,'KPP_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PASP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Паспортные данные плательщика.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PASP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PASP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'PASP','Паспортные данные плательщика.','STRING',1000,0,0,0,'PASP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Номер банковского счета плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'BS_PL','Номер банковского счета плательщика','STRING',20,1,0,0,'BS_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Должность руководителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DOL_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 22,'DOL_RUK','Должность руководителя','STRING',100,0,1,1,'DOL_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'ФИО руководителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 23,'NAME_RUK','ФИО руководителя','STRING',50,0,1,0,'NAME_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Должность ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DOL_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 24,'DOL_ISP','Должность ответственного исполнителя','STRING',100,0,1,1,'DOL_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'ФИО ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 25,'NAME_ISP','ФИО ответственного исполнителя','STRING',50,0,1,1,'NAME_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Телефон ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TEL_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 26,'TEL_ISP','Телефон ответственного исполнителя','STRING',50,0,0,0,'TEL_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Дата подписания документа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_POD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 27,'DATE_POD','Дата подписания документа','DATE',NULL,0,1,0,'DATE_POD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Должность руководителя ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_RUK_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'DOL_RUK_TOFK','Должность руководителя ОрФК','STRING',100,0,0,0,'DOL_RUK_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Руководитель ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_RUK_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 29,'NAME_RUK_TOFK','Руководитель ОрФК','STRING',50,0,0,0,'NAME_RUK_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Должность исполнителя ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_ISP_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 30,'DOL_ISP_TOFK','Должность исполнителя ОрФК','STRING',100,0,0,0,'DOL_ISP_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'Исполнитель ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_ISP_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 31,'NAME_ISP_TOFK','Исполнитель ОрФК','STRING',50,0,0,0,'NAME_ISP_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Телефон исполнителя ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TEL_ISP_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'TEL_ISP_TOFK','Телефон исполнителя ОрФК','STRING',50,0,0,0,'TEL_ISP_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Дата отметки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 33,'DATE_TOFK','Дата отметки','DATE',NULL,0,0,0,'DATE_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'UFPP'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'UFPP',5,2,'Реквизиты уточняемого платежного документа',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Реквизиты уточняемого платежного документа',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LINE_NOM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер записи',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'LINE_NOM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LINE_NOM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'LINE_NOM','Номер записи','NUMBER',NULL,0,1,1,'LINE_NOM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Глобальный идентификатор платежного документа',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'GUID','Глобальный идентификатор платежного документа','GUID',NULL,0,0,0,'GUID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код платежного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'KOD_DOC','Код платежного документа','STRING',2,1,1,0,'KOD_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Наименование платежного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NAME_PP','Наименование платежного документа','STRING',160,0,1,0,'NAME_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Номер платежного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NOM_PP','Номер платежного документа','STRING',15,0,1,0,'NOM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Дата платежного документа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'DATE_PP','Дата платежного документа','DATE',NULL,0,1,0,'DATE_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'CNAME_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'CNAME_PP','Наименование получателя','STRING',160,0,1,0,'CNAME_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'ИНН получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'INN_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'INN_PP','ИНН получателя','STRING',12,0,1,1,'INN_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'КПП получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KPP_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'KPP_PP','КПП получателя','STRING',9,0,1,1,'KPP_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Код по ОКАТО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKATO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'OKATO','Код по ОКАТО','STRING',11,1,0,0,'OKATO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'KBK','Код по КБК','STRING',20,1,1,1,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'TYPE_KBK','Тип КБК','STRING',2,1,1,1,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Код цели',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'ADD_KLASS','Код цели','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'SUM_PP','Сумма','NUMBER2',NULL,0,1,1,'SUM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'PURPOSE','Назначение платежа','STRING',210,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Номер заявки на кассовый расход',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_ZR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'NOM_ZR','Номер заявки на кассовый расход','STRING',15,0,0,0,'NOM_ZR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Дата заявки на кассовый расход',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_ZR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'DATE_ZR','Дата заявки на кассовый расход','DATE',NULL,0,0,0,'DATE_ZR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'NOTE','Примечание','STRING',254,0,0,0,'NOTE','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'UFPP_N'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'UFPP_N',6,2,'Новые реквизиты платежного документа',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Новые реквизиты платежного документа',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LINE_NOM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер записи',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'LINE_NOM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LINE_NOM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'LINE_NOM','Номер записи','NUMBER',NULL,0,1,1,'LINE_NOM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'CNAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'CNAME_UBP','Наименование получателя','STRING',160,0,1,0,'CNAME_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'ИНН получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'INN_UBP','ИНН получателя','STRING',12,0,1,0,'INN_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'КПП получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KPP_UBP','КПП получателя','STRING',9,0,1,0,'KPP_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Код по ОКАТО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKATO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'OKATO','Код по ОКАТО','STRING',11,1,1,0,'OKATO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Лицевой счет Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'LS_UBP','Лицевой счет Получателя','STRING',11,1,1,0,'LS_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'KBK','Код по КБК','STRING',20,1,1,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'TYPE_KBK','Тип КБК','STRING',2,1,1,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Код цели',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'ADD_KLASS','Код цели','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Уточняемая сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'SUM','Уточняемая сумма','NUMBER2',NULL,0,0,0,'SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'PURPOSE','Назначение платежа','STRING',210,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FUND_SOURCE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Вид средств',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'FUND_SOURCE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FUND_SOURCE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'FUND_SOURCE','Вид средств','STRING',1,1,0,0,'FUND_SOURCE','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = '2013.08' AND CODE = 'ZF'
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 'ZF','Заявка на финансирование','2013.08',0,'','XXXXXDNN.TTM','fb_file_name_doc','FB_EXPORT_ZF','cObjCode'',''&cModelVer','KOD_BP','',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_ZF',
		PROC_DOP_PARAM   = 'cObjCode'',''&cModelVer',
		PROG_SAVE   = '',
		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	= 0,
		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,0,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	= 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, 1,'KOD_BP','Код бюджетополучателя','STRING',5,0,0,1,'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	= 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, 2,'NAME_BP','Наименование бюджетополучателя','STRING',512,0,0,1,'NAME_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_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ФО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_FO','Код ФО','STRING',5,0,0,1,'KOD_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ФО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_FO','Наименование ФО','STRING',512,0,0,1,'NAME_FO','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZF'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZF',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 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID','Уникальный идентификатор документа','GUID',0,0,0,0,'GUID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUMBER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= '№ заявки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		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, 2,'NUMBER','№ заявки','STRING',15,0,0,1,'NUMBER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Дата',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE',
		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, 3,'DATE','Дата','DATE',NULL,0,1,1,'DATE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Сумма заявки',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUMMA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA'
else		
	INSERT INTO EXPORT_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,'SUMMA','Сумма заявки','NUMBER2',NULL,0,0,1,'SUMMA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		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, 5,'KOD_BP','Код отправителя','STRING',5,1,1,1,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_SEND')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		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, 6,'ACC_SEND','Счет отправителя','STRING',20,0,0,0,'ACC_SEND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Наименование отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		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, 7,'NAME_BP','Наименование отправителя','STRING',512,0,0,1,'NAME_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ANALITICS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		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, 8,'ANALITICS','Аналитические признаки','STRING',250,0,0,0,'ANALITICS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_EXEC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Дата вступления в силу',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		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, 9,'DATE_EXEC','Дата вступления в силу','DATE',NULL,0,0,0,'DATE_EXEC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_BEGIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Дата начала периода',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		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, 10,'DATE_BEGIN','Дата начала периода','DATE',0,0,0,0,'DATE_BEGIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PERIOD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		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, 11,'PERIOD','Период ведения документа','STRING',1,1,1,1,'PERIOD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BUD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'NAME_BUD','Наименование бюджета','STRING',512,0,1,1,'NAME_BUD','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZFST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZFST',5,2,'Строки заявки',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Строки заявки',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		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, 1,'KOD_BP','Код получателя','STRING',5,0,1,1,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		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, 2,'ACC_RCP','Счет получателя','STRING',20,0,0,0,'ACC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		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, 3,'NAME_BP','Наименование получателя','STRING',512,0,0,1,'NAME_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код по ППП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GLAVA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA'
else		
	INSERT INTO EXPORT_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,'GLAVA','Код по ППП','STRING',3,1,1,0,'GLAVA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'RAZDEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Код по ФКР',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'RAZDEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'RAZDEL'
else		
	INSERT INTO EXPORT_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,'RAZDEL','Код по ФКР','STRING',4,1,1,0,'RAZDEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'STATIA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Код по КЦСР',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 7,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'STATIA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'STATIA'
else		
	INSERT INTO EXPORT_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,'STATIA','Код по КЦСР','STRING',7,1,0,0,'STATIA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Код по КВР',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		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, 7,'VID','Код по КВР','STRING',3,1,0,0,'VID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'E_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Код по ЭКР',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'E_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'E_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, 8,'E_KLASS','Код по ЭКР','STRING',3,1,0,0,'E_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KKIVNF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Код КИВнФ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KKIVNF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KKIVNF'
else		
	INSERT INTO EXPORT_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,'KKIVNF','Код КИВнФ','STRING',20,1,0,0,'KKIVNF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KKIVF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Код КИВФ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KKIVF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KKIVF'
else		
	INSERT INTO EXPORT_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,'KKIVF','Код КИВФ','STRING',20,1,0,0,'KKIVF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KDOH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Код дохода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KDOH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KDOH'
else		
	INSERT INTO EXPORT_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,'KDOH','Код дохода','STRING',20,1,0,0,'KDOH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		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, 12,'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 		= 13,
		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, 13,'LOCAL','Региональная классификация','STRING',20,0,0,0,'LOCAL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Сумма по классификации',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUMMA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA'
else		
	INSERT INTO EXPORT_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,'SUMMA','Сумма по классификации','NUMBER2',0,0,0,1,'SUMMA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA1')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Сумма за 1-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA1',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA1'
else		
	INSERT INTO EXPORT_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,'SUMMA1','Сумма за 1-й интервал периода','NUMBER2',0,0,0,0,'SUMMA1','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA2')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Сумма за 2-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA2',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA2'
else		
	INSERT INTO EXPORT_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,'SUMMA2','Сумма за 2-й интервал периода','NUMBER2',0,0,0,0,'SUMMA2','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA3')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Сумма за 3-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA3',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA3'
else		
	INSERT INTO EXPORT_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,'SUMMA3','Сумма за 3-й интервал периода','NUMBER2',0,0,0,0,'SUMMA3','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA4')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Сумма за 4-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA4',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA4'
else		
	INSERT INTO EXPORT_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,'SUMMA4','Сумма за 4-й интервал периода','NUMBER2',0,0,0,0,'SUMMA4','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA5')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Сумма за 5-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA5',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA5'
else		
	INSERT INTO EXPORT_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,'SUMMA5','Сумма за 5-й интервал периода','NUMBER2',0,0,0,0,'SUMMA5','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA6')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Сумма за 6-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA6',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA6'
else		
	INSERT INTO EXPORT_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,'SUMMA6','Сумма за 6-й интервал периода','NUMBER2',0,0,0,0,'SUMMA6','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA7')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Сумма за 7-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA7',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA7'
else		
	INSERT INTO EXPORT_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,'SUMMA7','Сумма за 7-й интервал периода','NUMBER2',0,0,0,0,'SUMMA7','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA8')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Сумма за 8-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA8',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA8'
else		
	INSERT INTO EXPORT_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,'SUMMA8','Сумма за 8-й интервал периода','NUMBER2',0,0,0,0,'SUMMA8','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA9')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Сумма за 9-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA9',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA9'
else		
	INSERT INTO EXPORT_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,'SUMMA9','Сумма за 9-й интервал периода','NUMBER2',0,0,0,0,'SUMMA9','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA10')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Сумма за 10-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA10',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA10'
else		
	INSERT INTO EXPORT_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,'SUMMA10','Сумма за 10-й интервал периода','NUMBER2',0,0,0,0,'SUMMA10','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA11')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Сумма за 11-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA11',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA11'
else		
	INSERT INTO EXPORT_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,'SUMMA11','Сумма за 11-й интервал периода','NUMBER2',0,0,0,0,'SUMMA11','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA12')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Сумма за 12-й интервал периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA12',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA12'
else		
	INSERT INTO EXPORT_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,'SUMMA12','Сумма за 12-й интервал периода','NUMBER2',0,0,0,0,'SUMMA12','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM_STR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Примечание к строке',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 255,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PRIM_STR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM_STR'
else		
	INSERT INTO EXPORT_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,'PRIM_STR','Примечание к строке','STRING',255,0,0,0,'PRIM_STR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Номер БО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'NUM_BO','Номер БО','STRING',16,0,0,0,'NUM_BO','',''
GO

GO
update EXPORT_MODELS set DATE_END   = '20151231' where MODEL_VER = 'TXZN150101' AND CODE = 'ZN'
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXZN160101' AND CODE = 'ZN'
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 'ZN','Заявка на получение денежных средств, перечисляемых на карту','TXZN160101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_ZN_16','','KOD_UBP','',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Заявка на получение денежных средств, перечисляемых на карту',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_ZN_16',
		PROC_DOP_PARAM   = '',
		PROG_SAVE   = '',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,0,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NAME_UBP','Наименование УБП','STRING',254,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZN'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZN',4,2,'Общая инфор-мация',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Общая инфор-мация',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID_FK','Глобальный уникальный идентификатор','STRING',36,0,0,0,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Номер заявки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_ZN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NOM_ZN','Номер заявки','STRING',15,0,1,1,'NOM_ZN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Дата заявки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_ZN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'DATE_ZN','Дата заявки','DATE',0,1,1,1,'DATE_ZN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код ПБС по Сводному ре-естру',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KOD_UBP','Код ПБС по Сводному ре-естру','STRING',5,1,0,0,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Наименование клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NAME_UBP','Наименование клиента','STRING',2000,0,1,1,'NAME_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Код органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'KOD_TOFK','Код органа ФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Наименование органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'NAME_TOFK','Наименование органа ФК','STRING',2000,0,1,1,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Номер лицевого счета клиента.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'LS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'LS_PAY','Номер лицевого счета клиента.','STRING',11,1,1,1,'LS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Номер обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 19,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'NOM_BO','Номер обязательства','STRING',19,1,0,0,'NOM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FAIP_CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Код объекта по ФАИП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 14,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'FAIP_CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FAIP_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, 10,'FAIP_CODE','Код объекта по ФАИП','STRING',14,1,0,0,'FAIP_CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'ИНН',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'INN_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'INN_UBP','ИНН','STRING',10,1,0,1,'INN_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'КПП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KPP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'KPP','КПП','STRING',9,1,0,1,'KPP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CARD_NUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Номер банков-ской карты',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CARD_NUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CARD_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, 13,'CARD_NUM','Номер банков-ской карты','STRING',20,0,0,1,'CARD_NUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_V_SR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Вид средств',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_V_SR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_V_SR'
else		
	INSERT INTO EXPORT_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_V_SR','Вид средств','STRING',1,1,0,1,'NAME_V_SR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Должность вла-дельца банков-ской карты',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DOL_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'DOL_ISP','Должность вла-дельца банков-ской карты','STRING',100,0,0,1,'DOL_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_F')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Фамилия вла-дельца банков-ской карты',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 40,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'ISP_F',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_F'
else		
	INSERT INTO EXPORT_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,'ISP_F','Фамилия вла-дельца банков-ской карты','STRING',40,0,0,1,'ISP_F','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_I')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Имя владельца банковской карты',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'ISP_I',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_I'
else		
	INSERT INTO EXPORT_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,'ISP_I','Имя владельца банковской карты','STRING',20,0,0,1,'ISP_I','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_O')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Отчество вла-дельца банков-ской карты',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 30,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'ISP_O',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_O'
else		
	INSERT INTO EXPORT_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,'ISP_O','Отчество вла-дельца банков-ской карты','STRING',30,0,0,1,'ISP_O','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Должность руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DOL_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'DOL_RUK','Должность руководителя (уполномоченного им лица)','STRING',100,0,0,1,'DOL_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'ФИО руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'NAME_RUK','ФИО руководителя (уполномоченного им лица)','STRING',50,0,0,1,'NAME_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_BUH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Должность главного бухгалтера (уполномоченного руководителем лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_BUH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_BUH'
else		
	INSERT INTO EXPORT_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,'DOL_BUH','Должность главного бухгалтера (уполномоченного руководителем лица)','STRING',100,0,0,0,'DOL_BUH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'ФИО главного бухгалтера (уполномоченного руководителем лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BUH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUH'
else		
	INSERT INTO EXPORT_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,'NAME_BUH','ФИО главного бухгалтера (уполномоченного руководителем лица)','STRING',50,0,0,0,'NAME_BUH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Дата подписания заявки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_POD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 23,'DATE_POD','Дата подписания заявки','DATE',0,0,0,1,'DATE_POD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA_ITOG')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Сумма денежных средств',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUMMA_ITOG',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA_ITOG'
else		
	INSERT INTO EXPORT_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,'SUMMA_ITOG','Сумма денежных средств','NUMBER2',0,1,1,1,'SUMMA_ITOG','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA_R2')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Общая сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUMMA_R2',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA_R2'
else		
	INSERT INTO EXPORT_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,'SUMMA_R2','Общая сумма','NUMBER2',0,1,1,1,'SUMMA_R2','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZNKBK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZNKBK',5,2,'Расшифровка заявки',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Расшифровка заявки',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'POR_NUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Порядковый номер',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 8,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'POR_NUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'POR_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, 1,'POR_NUM','Порядковый номер','NUMBER',8,0,0,1,'POR_NUM','',''
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	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KBK','Код по БК','STRING',20,1,1,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'TYPE_KBK','Тип КБК','STRING',2,1,1,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 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 = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'PURPOSE','Назначение платежа','STRING',210,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMR_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Сумма в рублях',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMR_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMR_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, 6,'SUMR_KBK','Сумма в рублях','NUMBER2',0,1,1,0,'SUMR_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'NOTE','Примечание','STRING',2000,0,0,0,'NOTE','',''
GO

GO
update EXPORT_MODELS set DATE_END   = '20151231' where MODEL_VER = 'TXZR150101' AND CODE = 'ZR'
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXZR160101' AND CODE = 'ZR'
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 'ZR','Заявка на кассовый расход','TXZR160101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_ZKR_16','cModelVer','KOD_UBP','bb_import_zkr()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Заявка на кассовый расход',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_ZKR_16',
		PROC_DOP_PARAM   = 'cModelVer',
		PROG_SAVE   = 'bb_import_zkr()',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,0,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NAME_UBP','Наименование УБП','STRING',254,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZR'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZR',4,2,'Общая информация',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Общая информация',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID_FK','Глобальный уникальный идентификатор','STRING',36,0,0,0,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип заявки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'TYPE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = '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, 2,'TYPE','Тип заявки','STRING',1,1,1,1,'TYPE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Номер заявки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_ZR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NOM_ZR','Номер заявки','STRING',15,0,1,1,'NOM_ZR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Дата заявки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_ZR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'DATE_ZR','Дата заявки','DATE',0,1,1,1,'DATE_ZR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Код клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'KOD_UBP_PAY','Код клиента','STRING',5,0,0,0,'KOD_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Наименование клиентаклиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'NAME_UBP_PAY','Наименование клиентаклиента','STRING',2000,0,1,1,'NAME_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Номер лицевого счета клиента.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'LS_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'LS_UBP_PAY','Номер лицевого счета клиента.','STRING',11,1,1,1,'LS_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'ИНН клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'INN_UBP','ИНН клиента','STRING',10,1,0,0,'INN_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'КПП клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'KPP_UBP','КПП клиента','STRING',9,1,0,0,'KPP_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Глава по БК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GLAVA_GRS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'GLAVA_GRS','Глава по БК','STRING',3,1,0,0,'GLAVA_GRS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_GRS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Наименование ГРБС (ГАИФДБ)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP_GRS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_GRS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'NAME_UBP_GRS','Наименование ГРБС (ГАИФДБ)','STRING',2000,0,1,0,'NAME_UBP_GRS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		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, 12,'NAME_BUD','Наименование бюджета','STRING',512,0,0,0,'NAME_BUD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Наименование финансового органа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'NAME_FO','Наименование финансового органа','STRING',2000,0,1,0,'NAME_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKPO_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Код по ОКПО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 8,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKPO_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKPO_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'OKPO_FO','Код по ОКПО','STRING',8,1,0,0,'OKPO_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Код органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'KOD_TOFK','Код органа ФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Наименование органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'NAME_TOFK','Наименование органа ФК','STRING',2000,0,1,1,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Предельная дата исполнения',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'DATE_ISP','Предельная дата исполнения','DATE',0,1,1,0,'DATE_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_SV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Идентификатор документа "Све-дения о принятом бюджетном обя-зательстве", предоставленного в ОрФК',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_SV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_SV'
else		
	INSERT INTO EXPORT_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,'GUID_SV','Идентификатор документа "Све-дения о принятом бюджетном обя-зательстве", предоставленного в ОрФК','GUID',0,0,0,0,'GUID_SV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Номер обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 19,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'NOM_BO','Номер обязательства','STRING',19,1,0,0,'NOM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Код приоритета исполнения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'KOD_ISP','Код приоритета исполнения','STRING',1,1,0,0,'KOD_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PR_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Приоритет исполнения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PR_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PR_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'PR_ISP','Приоритет исполнения','STRING',250,0,0,0,'PR_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FAIP_CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Код объекта по ФАИП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 14,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'FAIP_CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FAIP_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, 22,'FAIP_CODE','Код объекта по ФАИП','STRING',14,1,0,0,'FAIP_CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_V')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Сумма документа в валюте выплаты',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_V',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_V'
else		
	INSERT INTO EXPORT_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,'SUM_V','Сумма документа в валюте выплаты','NUMBER2',0,1,0,1,'SUM_V','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_V')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Код валюты по ОКВ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_V',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_V'
else		
	INSERT INTO EXPORT_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,'KOD_V','Код валюты по ОКВ','STRING',3,1,0,1,'KOD_V','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Сумма документа',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_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, 25,'SUM_DOC','Сумма документа','NUMBER2',0,1,1,0,'SUM_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_AP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Признак авансового платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'TYPE_AP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_AP'
else		
	INSERT INTO EXPORT_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,'TYPE_AP','Признак авансового платежа','STRING',1,1,0,1,'TYPE_AP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Очередность платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'ORDER_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 27,'ORDER_PL','Очередность платежа','STRING',1,1,1,1,'ORDER_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Вид платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'VID_PL','Вид платежа','STRING',1,1,1,1,'VID_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 29,'PURPOSE','Назначение платежа','STRING',210,0,1,1,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Наименование / ФИО контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 30,'NAME_RCP','Наименование / ФИО контрагента','STRING',160,0,1,1,'NAME_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'ИНН контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'INN_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 31,'INN_RCP','ИНН контрагента','STRING',12,0,1,1,'INN_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'КПП контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KPP_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'KPP_RCP','КПП контрагента','STRING',9,0,1,1,'KPP_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Лицевой счет контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_UBP_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 33,'LS_UBP_RCP','Лицевой счет контрагента','STRING',11,1,0,0,'LS_UBP_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 34,
		NAME   		= 'Банковский счет контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 34,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 34,'BS_RCP','Банковский счет контрагента','STRING',34,0,0,0,'BS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 35,
		NAME   		= 'Наименование банка контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 35,'NAME_BIC_RCP','Наименование банка контрагента','STRING',160,0,0,1,'NAME_BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 36,
		NAME   		= 'БИК банка контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 36,'BIC_RCP','БИК банка контрагента','STRING',9,1,0,0,'BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KS_BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 37,
		NAME   		= 'Корсчет банка контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 34,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KS_BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KS_BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 37,'KS_BIC_RCP','Корсчет банка контрагента','STRING',34,0,0,0,'KS_BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 38,
		NAME   		= 'Статус налогоплательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PAYSTATUS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 38,'PAYSTATUS','Статус налогоплательщика','STRING',2,1,0,0,'PAYSTATUS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KDOH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 39,
		NAME   		= 'Код бюджетной классификации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KDOH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KDOH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 39,'KDOH','Код бюджетной классификации','STRING',20,1,0,0,'KDOH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 40,
		NAME   		= 'Код ОКАТО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKATO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 40,'OKATO','Код ОКАТО','STRING',11,0,0,0,'OKATO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSN_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 41,
		NAME   		= 'Показатель основания платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OSN_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSN_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 41,'OSN_PL','Показатель основания платежа','STRING',2,0,0,0,'OSN_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 42,
		NAME   		= 'Показатель налогового периода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAL_PER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 42,'NAL_PER','Показатель налогового периода','STRING',10,0,0,0,'NAL_PER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 43,
		NAME   		= 'Показатель номера документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 43,'NOM_DOK','Показатель номера документа','STRING',15,0,0,0,'NOM_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 44,
		NAME   		= 'Показатель даты документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 44,'DATE_DOK','Показатель даты документа','STRING',10,0,0,0,'DATE_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 45,
		NAME   		= 'Тип платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 45,'TYPE_PL','Тип платежа','STRING',2,0,0,0,'TYPE_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 46,
		NAME   		= 'Должность руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_RUK_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 46,'DOL_RUK_UBP','Должность руководителя (уполномоченного им лица)','STRING',100,0,0,0,'DOL_RUK_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 47,
		NAME   		= 'ФИО руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_RUK_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 47,'NAME_RUK_UBP','ФИО руководителя (уполномоченного им лица)','STRING',50,0,0,1,'NAME_RUK_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_BUH_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 48,
		NAME   		= 'Должность главного бухгалтера (уполномоченного руководителем лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_BUH_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_BUH_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 48,'DOL_BUH_UBP','Должность главного бухгалтера (уполномоченного руководителем лица)','STRING',100,0,0,0,'DOL_BUH_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUH_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 49,
		NAME   		= 'ФИО главного бухгалтера (уполномоченного руководителем лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BUH_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUH_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 49,'NAME_BUH_UBP','ФИО главного бухгалтера (уполномоченного руководителем лица)','STRING',50,0,0,0,'NAME_BUH_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 50,
		NAME   		= 'Дата подписания заявки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_POD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 50,'DATE_POD_UBP','Дата подписания заявки','DATE',0,0,0,1,'DATE_POD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZR_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 51,
		NAME   		= 'Отметка ОрФК о постановке на учет / Номер заявки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_ZR_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZR_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 51,'NOM_ZR_FK','Отметка ОрФК о постановке на учет / Номер заявки','STRING',15,0,0,0,'NOM_ZR_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 52,
		NAME   		= 'Отметка ОрФК о постановке на учет / Дата постановки на учет',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 52,'DATE_FK','Отметка ОрФК о постановке на учет / Дата постановки на учет','DATE',0,1,0,0,'DATE_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 53,
		NAME   		= 'Отметка ОрФК о постановке на учет / Должность ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_ISP_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 53,'DOL_ISP_FK','Отметка ОрФК о постановке на учет / Должность ответственного исполнителя','STRING',100,0,0,0,'DOL_ISP_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 54,
		NAME   		= 'Отметка ОрФК о постановке на учет / ФИО ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_ISP_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 54,'NAME_ISP_FK','Отметка ОрФК о постановке на учет / ФИО ответственного исполнителя','STRING',50,0,0,0,'NAME_ISP_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 55,
		NAME   		= 'Отметка ОрФК о постановке на учет / Телефон ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TEL_ISP_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 55,'TEL_ISP_FK','Отметка ОрФК о постановке на учет / Телефон ответственного исполнителя','STRING',50,0,0,0,'TEL_ISP_FK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZROSN'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZROSN',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 = 'OSN_PLAT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Признак основания платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OSN_PLAT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSN_PLAT'
else		
	INSERT INTO EXPORT_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,'OSN_PLAT','Признак основания платежа','STRING',1,0,0,0,'OSN_PLAT','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OSN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Вид документа-основания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_OSN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OSN'
else		
	INSERT INTO EXPORT_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,'VID_OSN','Вид документа-основания','STRING',50,0,0,1,'VID_OSN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_OSN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Номер документа-основания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_OSN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_OSN'
else		
	INSERT INTO EXPORT_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,'NOM_OSN','Номер документа-основания','STRING',100,0,0,1,'NOM_OSN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_OSN')
	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_OSN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_OSN'
else		
	INSERT INTO EXPORT_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_OSN','Дата документа-основания','DATE',NULL,0,0,0,'DATE_OSN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Предмет документа-основания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OSN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSN'
else		
	INSERT INTO EXPORT_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,'OSN','Предмет документа-основания','STRING',512,0,0,0,'OSN','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZRST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZRST',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 = 'KOD_IST_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Источник средств',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_IST_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_IST_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,'KOD_IST_KBK','Источник средств','STRING',1,1,0,1,'KOD_IST_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип КБК плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK_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, 2,'TYPE_KBK_PAY','Тип КБК плательщика','STRING',2,1,1,0,'TYPE_KBK_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код по БК плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK_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, 3,'KBK_PAY','Код по БК плательщика','STRING',20,1,1,0,'KBK_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Тип КБК получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'TYPE_KBK_RCP','Тип КБК получателя','STRING',2,1,0,0,'TYPE_KBK_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Код по БК получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK_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, 5,'KBK_RCP','Код по БК получателя','STRING',20,1,0,0,'KBK_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Код цели субсидии / субвенции плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS_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, 6,'ADD_KLASS_PAY','Код цели субсидии / субвенции плательщика','STRING',20,0,0,0,'ADD_KLASS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Код цели субсидии / субвенции получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'ADD_KLASS_RCP','Код цели субсидии / субвенции получателя','STRING',20,0,0,0,'ADD_KLASS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_V_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Сумма в валюте заявки',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_V_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_V_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'SUM_V_KBK','Сумма в валюте заявки','NUMBER2',0,1,0,1,'SUM_V_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_R_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Сумма в рублях',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_R_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_R_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, 9,'SUM_R_KBK','Сумма в рублях','NUMBER2',0,1,1,0,'SUM_R_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE_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, 10,'PURPOSE_KBK','Назначение платежа','STRING',210,0,0,0,'PURPOSE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'NOTE_KBK','Примечание','STRING',254,0,0,0,'NOTE_KBK','',''
GO

GO
update EXPORT_MODELS set DATE_END   = '20151231' where MODEL_VER = 'TXZS140101' AND CODE = 'ZS'
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXZS160101' AND CODE = 'ZS'
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 'ZS','Заявка на получение наличных денег','TXZS160101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_ZS_16','','KOD_UBP','',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Заявка на получение наличных денег',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_ZS_16',
		PROC_DOP_PARAM   = '',
		PROG_SAVE   = '',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,0,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NAME_UBP','Наименование УБП','STRING',254,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZS'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZS',4,2,'Заявка',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Заявка',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID_FK','Глобальный уникальный идентификатор','STRING',36,0,0,0,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZVK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Номер заявки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_ZVK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZVK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NOM_ZVK','Номер заявки','STRING',15,0,1,1,'NOM_ZVK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZVK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Дата заявки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_ZVK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZVK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'DATE_ZVK','Дата заявки','DATE',0,1,1,1,'DATE_ZVK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		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, 4,'NAME_BUD','Наименование бюджета','STRING',512,0,1,0,'NAME_BUD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Наименование финансового органа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NAME_UBP_FO','Наименование финансового органа','STRING',2000,0,1,0,'NAME_UBP_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKPO_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Код по ОКПО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 8,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKPO_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKPO_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'OKPO_FO','Код по ОКПО','STRING',8,1,0,0,'OKPO_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_GRBS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Наименование ГРБС (ГАИФДБ)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_GRBS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_GRBS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'NAME_GRBS','Наименование ГРБС (ГАИФДБ)','STRING',2000,0,1,0,'NAME_GRBS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRBS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Глава по БК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GLAVA_GRBS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRBS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'GLAVA_GRBS','Глава по БК','STRING',3,1,1,0,'GLAVA_GRBS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Наименование клиентаклиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'NAME_UBP_PAY','Наименование клиентаклиента','STRING',2000,0,1,1,'NAME_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Код клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'KOD_UBP_PAY','Код клиента','STRING',5,1,0,0,'KOD_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Номер лицевого счета клиента.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'LS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'LS_PAY','Номер лицевого счета клиента.','STRING',11,1,1,1,'LS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Наименование органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'NAME_TOFK','Наименование органа ФК','STRING',2000,0,1,1,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Код органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'KOD_TOFK','Код органа ФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_LIM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Предельная дата исполнения',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_LIM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_LIM'
else		
	INSERT INTO EXPORT_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,'DATE_LIM','Предельная дата исполнения','DATE',0,1,1,0,'DATE_LIM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Номер обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 19,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'NOM_BO','Номер обязательства','STRING',19,1,0,0,'NOM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Должность руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'DOL_RUK','Должность руководителя (уполномоченного им лица)','STRING',100,0,0,0,'DOL_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'ФИО руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'NAME_RUK','ФИО руководителя (уполномоченного им лица)','STRING',50,0,0,1,'NAME_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_BUH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Должность главного бухгалтера (уполномоченного руководителем лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_BUH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_BUH'
else		
	INSERT INTO EXPORT_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,'DOL_BUH','Должность главного бухгалтера (уполномоченного руководителем лица)','STRING',100,0,0,0,'DOL_BUH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'ФИО главного бухгалтера (уполномоченного руководителем лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BUH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'NAME_BUH','ФИО главного бухгалтера (уполномоченного руководителем лица)','STRING',50,0,0,0,'NAME_BUH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Дата подписания заявки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_POD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'DATE_POD','Дата подписания заявки','DATE',0,0,0,1,'DATE_POD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_DOV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Должность довененного лица',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DOL_ISP_DOV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_DOV'
else		
	INSERT INTO EXPORT_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,'DOL_ISP_DOV','Должность довененного лица','STRING',100,0,0,1,'DOL_ISP_DOV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_DOV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'ФИО довененного лица',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_ISP_DOV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_DOV'
else		
	INSERT INTO EXPORT_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,'NAME_ISP_DOV','ФИО довененного лица','STRING',50,0,0,1,'NAME_ISP_DOV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_DOV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Наименование документа, удостоверяющего личность',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 255,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_DOV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_DOV'
else		
	INSERT INTO EXPORT_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_DOV','Наименование документа, удостоверяющего личность','STRING',255,0,0,1,'NAME_DOV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Номер документа, удостоверяющего личность',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 45,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_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, 24,'NOM_DOC','Номер документа, удостоверяющего личность','STRING',45,0,0,0,'NOM_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORG_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Кем выдан документ, удостоверяющий личность',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ORG_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ORG_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, 25,'ORG_DOC','Кем выдан документ, удостоверяющий личность','STRING',2000,0,0,0,'ORG_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Дата документа, удостоверяющего личность',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_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, 26,'DATE_DOC','Дата документа, удостоверяющего личность','DATE',0,1,0,0,'DATE_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_ITOG')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Сумма документа',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_ITOG',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_ITOG'
else		
	INSERT INTO EXPORT_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_ITOG','Сумма документа','NUMBER2',0,1,1,0,'SUM_ITOG','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZS_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Номер заявки, присвоеный ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_ZS_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZS_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'NOM_ZS_FK','Номер заявки, присвоеный ОрФК','STRING',15,0,0,0,'NOM_ZS_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Дата регистрации заявки в ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 29,'DATE_FK','Дата регистрации заявки в ОрФК','STRING',10,0,0,0,'DATE_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Должность ответственого исполнителя в ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_ISP_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 30,'DOL_ISP_FK','Должность ответственого исполнителя в ФК','STRING',100,0,0,0,'DOL_ISP_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'ФИО  ответственого исполнителя в ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_ISP_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 31,'NAME_ISP_FK','ФИО  ответственого исполнителя в ФК','STRING',50,0,0,0,'NAME_ISP_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Телефон  ответственого исполнителя в ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TEL_ISP_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'TEL_ISP_FK','Телефон  ответственого исполнителя в ФК','STRING',10,0,0,0,'TEL_ISP_FK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZSCH1'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZSCH1',5,2,'Реквизиты чека',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Реквизиты чека',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMR_ZVK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUMR_ZVK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMR_ZVK'
else		
	INSERT INTO EXPORT_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,'SUMR_ZVK','сумма','NUMBER2',0,0,1,1,'SUMR_ZVK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CHEСK_NOM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Номер чека',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CHECK_NOM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CHEСK_NOM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'CHEСK_NOM','Номер чека','STRING',15,0,0,1,'CHECK_NOM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CHECK_SER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Серия чека',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 30,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CHECK_SER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CHECK_SER'
else		
	INSERT INTO EXPORT_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,'CHECK_SER','Серия чека','STRING',30,0,0,1,'CHECK_SER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_CHEСK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Дата оформления чека',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_CHECK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_CHEСK'
else		
	INSERT INTO EXPORT_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_CHEСK','Дата оформления чека','DATE',0,1,0,1,'DATE_CHECK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_CHEСK_LIM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Срок действия чека',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_CHECK_LIM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_CHEСK_LIM'
else		
	INSERT INTO EXPORT_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_CHEСK_LIM','Срок действия чека','DATE',0,1,0,1,'DATE_CHECK_LIM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CHECK_KAS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Символ кассового плана',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CHECK_KAS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CHECK_KAS'
else		
	INSERT INTO EXPORT_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,'CHECK_KAS','Символ кассового плана','STRING',2,1,1,1,'CHECK_KAS','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZSCH2'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZSCH2',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 = 'KOD_IST')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Источник средств',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_IST',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_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, 1,'KOD_IST','Источник средств','STRING',1,1,0,1,'KOD_IST','',''
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	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KBK','Код по БК','STRING',20,1,1,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'TYPE_KBK','Тип КБК','STRING',2,1,1,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 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 = 'SUMR_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Сумма в рублях',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMR_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMR_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, 5,'SUMR_KBK','Сумма в рублях','NUMBER2',0,1,1,0,'SUMR_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'PURPOSE','Назначение платежа','STRING',210,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'NOTE','Примечание','STRING',254,0,0,0,'NOTE','',''
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 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			  
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '320')
	IF EXISTS(SELECT * FROM DICTIONARY_TYP_DEDUCTION WHERE code = '320' AND link != @LINK_DICT)
	BEGIN
		DELETE FROM DICTIONARY_TYP_DEDUCTION WHERE code = '320'
		
		IF NOT EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION  WHERE code = '320')
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  ON
			INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (LINK, SNAME,NAME,CODE,NUMBER,SUMMA)
			VALUES(@LINK_DICT, '320','Сумма, уплаченная налогоплательщиком за свое обучение в образовательных учреждениях, за обучение брата(сестры) в возрасте до 24 лет по очной форме обучения','320',11,0.00)
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  OFF

	END
	SET @LINK_DICT = 0
END 

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

IF 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			  
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '321')
	IF EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE code = '321' AND link != @LINK_DICT)
	BEGIN
		DELETE FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE code = '321'
		
		IF NOT EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION  WHERE code = '321')
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  ON
			INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (LINK, SNAME,NAME,CODE,NUMBER,SUMMA)
			VALUES(@LINK_DICT,'321',LEFT('Сумма, уплаченная налогоплательщиком-родителем за обуч. своих детей в возрасте до 24 лет, налогоплательщиком-опекуном/попечителем за обучение своих подопечных в возрасте до 18 лет по очной форме обучения,или после прекращения опеки или попечительства в случаях оплаты обучения граждан в возрасте до 24 лет по очной форме обучения ', 254),'321',11,0.00)
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  OFF

	END
	SET @LINK_DICT = 0
END 

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

IF 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			  
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '324')
	IF EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE code = '324' AND link != @LINK_DICT)
	BEGIN
		DELETE FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE code = '324'
		
		IF NOT EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION  WHERE code = '324')
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  ON
			INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (LINK, SNAME,NAME,CODE,NUMBER,SUMMA)
			VALUES(@LINK_DICT,'324',LEFT('Сумма, уплаченная налогоплательщиком за мед. услуги, оказанные мед. организациями, индивидуальными предпринимателями, осуществляющими мед. деятельность, ему, его супругу (супруге), родителям, детям (в том числе усыновленным) в возрасте до 18 лет, подопечным в возрасте до 18 лет (в соответствии с перечнем мед. услуг), а также в размере стоимости лекарственных препаратов для мед. применения (в соответствии с перечнем лекарственных средств), назначенных им лечащим врачом и приобретаемых налогоплательщиком за счет собственных средств', 254),'324',12,0.00)
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  OFF

	END
	SET @LINK_DICT = 0
END 
-------------------------------------------
 
IF 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			  
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '325')
	IF EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE code = '325' AND link != @LINK_DICT)
	BEGIN
		DELETE FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE code = '325'
		
		IF NOT EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION  WHERE code = '325')
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  ON
			INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (LINK, SNAME,NAME,CODE,NUMBER,SUMMA)
			VALUES(@LINK_DICT,'325',LEFT('Суммы страховых взносов, уплаченные налогоплательщиком по договорам добровольного личного страх., а также по договорам добровольного страх. своих супруга (супруги), родителей, детей (в том числе усыновленных) в возрасте до 18 лет, подопечных в возрасте до 18 лет, заключенным им со страх. организациями, имеющими лицензии на ведение соответствующего вида деятельности, предусматривающим оплату такими страх. организациями исключительно мед. услуг', 254),'325',12,0.00)
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  OFF

	END
	SET @LINK_DICT = 0
END 
---------------------------
 
IF 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			  
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '326')
	IF EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE code = '326' AND link != @LINK_DICT)
	BEGIN
		DELETE FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE code = '326'
		
		IF NOT EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION  WHERE code = '326')
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  ON
			INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (LINK, SNAME,NAME,CODE,NUMBER,SUMMA)
			VALUES(@LINK_DICT, '326',LEFT('Сумма расходов по дорогостоящему лечению в мед. организациях, у индивидуальных предпринимателей, осуществляющих мед. деятельность, - в размере фактически произведенных расходов', 254),'326',12,0.00)
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  OFF

	END
	SET @LINK_DICT = 0
END 

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

IF 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			  
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '327')
	IF EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE code = '327' AND link != @LINK_DICT)
	BEGIN
		DELETE FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE code = '327'
		
		IF NOT EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION  WHERE code = '327')
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  ON
			INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (LINK, SNAME,NAME,CODE,NUMBER,SUMMA)
			VALUES(@LINK_DICT,'327',LEFT('Сумма уплаченных налогоплательщиком пенсионных взносов по договору (договорам) негосударственного пенсионного обеспечения, в сумме уплаченных налогоплательщиком в налоговом периоде страх. взносов по договору (договорам) добровольного пенс. страх. в свою пользу и (или) в пользу супруга (в том числе вдовы, вдовца), родителей (в том числе усыновителей), детей-инвалидов (в том числе усыновленных, находящихся под опекой (попечительством)', 254),'327',13,0.00)
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  OFF

	END
	SET @LINK_DICT = 0
END 

-------------------------------------
IF 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			  
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '328')
	IF EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE code = '328' AND link != @LINK_DICT)
	BEGIN
		DELETE FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE code = '328'
		
		IF NOT EXISTS(SELECT * FROM dbo.DICTIONARY_TYP_DEDUCTION  WHERE code = '328')
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  ON
			INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (LINK, SNAME,NAME,CODE,NUMBER,SUMMA)
			VALUES(@LINK_DICT,'328',LEFT('Сумма уплаченных налогоплательщиком дополнительных страховых взносов на накопительную пенсию - в размере фактически произведенных расходов с учетом ограничения', 254),'328',13,0.00)
			SET IDENTITY_INSERT dbo.DICTIONARY_TYP_DEDUCTION  OFF

	END
	SET @LINK_DICT = 0
END 


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 'FINANS_ASSIGN_S_OPT_TYP_NAME', 'REFERENCE_TO_DICT', 'FINANS_ASSIGN_S_OPT_TYP_LINK'
GO

EXECUTE X_FORM_VIEW_OPTIONS 'FINANS_ASSIGN_S_OPTIONS' 
GO

GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (фев  8 2016  4:52:53:407PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503117M (Отчет об исполнении бюджета (месячный))
-- Дата ввода : 20160101
-- Дата окончания действия :
-- Версия : 2016-02-08 16:52:53.407
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0503117M' AND [START_DATE] = '20160101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2016-02-08 16:52:53.407',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0503117M',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0503117M'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20160101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SMETA'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Отчет об исполнении бюджета (месячный)',@vcNEW_FORM_CODE,@dNEW_START_DATE,4,1,1,1,18186,'RA_EXPORT_FORM_STANDART#RA_IMPORT_FORM_117',0,1,'19000101',NULL,'191н'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'svodprint_page_itog()','sv_0503117G_20090101.bas','','KirRepMakerMultiSheet.xls','sv_0503117M_20160101.xlt','',NULL,'RA_EXPORT_FORM_STANDART#RA_IMPORT_FORM_117',0,'RTRIM (COL2) + ''|$ADM$|'' + RTRIM (COL3) + ''|'' + STR(COL4) + ''|''  + STR(COL5) + ''|''  + STR(COL6) + ''|'' # RTRIM (COL2) + ''|$ADM$|'' + LEFT (COL9, 4) + ''|'' + SUBSTRING (COL9, 5, 10) + ''|'' + SUBSTRING (COL9, 15, 3)  + ''|''  + STR(COL7) + ''|'' + STR(COL8) + ''|'' + STR(COL9) + ''|'' # RTRIM(COL2) + ''|$ADM$|'' + RTRIM(COL3) + ''|'' + STR(COL4) + ''|'' + STR(COL5) + ''|'' + STR(COL6) + ''|''','C1 + ''|'' + C3 + ''|'' + C4 + ''|'' + C5 + ''|'' + C6 + ''|'' # C1 + ''|'' + C3 + C4 + C5 + C6 + ''|'' + C7 + ''|'' + C8 + ''|'' + C9 + ''|'' # C1 + C3 + ''|'' + C4 + ''|'' + C5 + ''|'' + C6 + ''|''',NULL,'117       ','REPORTS_ATR_ADM',NULL,'RO_PRINT_117_ITOG_16','|sv_0503117G_20091231_new.xlt',0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Доходы', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,1000,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Код дохода по бюджетной классификации',@iLINK_TABLE,1,1,3,0,0,1,'R_SPR_DOH_17_2011','COL1,COL2,COL3','LONG_NAME,CODE_STR,CODE','NNNNNNNNNN NNNN NNN',NULL,NULL,'%date% >= begin_date and %date% <= end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Утвержденные бюджетные назначения',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Исполнено',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Неисполненные назначения',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Доходы', @iLINK_FORM,1, @iLINK_CODE_COL,1,'CALC_SKELET=sql.call("dbo.RO_CALC_SKELET",m.cAlias,0x0,''0503117M'',1,''20110101'')
kbk=5,-6(Якутск)','-1#LEFT(CODE,3)=''850''',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Расходы', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,1500,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'РЗПР',@iLINK_TABLE,0,1,0,0,4,1,'R_SPR_RZPR_2011','COL3','CODE',NULL,NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'ЦСР',@iLINK_TABLE,0,1,0,0,10,1,'R_SPR_CSR_USER_2016','COL4','CODE',NULL,NULL,NULL,'dbo.RO_KBK_ORG_IS_VIEW(link, org, budg,%link_org%, %link_budg%, ''20110101'') = 1 AND %date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'ВР',@iLINK_TABLE,0,1,0,0,3,1,'R_SPR_VR_USER_2011','COL5,COL1,COL2','CODE,NAME,CODE_STR',NULL,NULL,NULL,'dbo.RO_KBK_ORG_IS_VIEW(link, org, budg,%link_org%, %link_budg%, ''20110101'') = 1 AND %date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Утвержденные бюджетные назначения',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Исполнено',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Неисполненные назначения',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Код расхода по ППП, ФКР, КЦСР, КВР, ЭКР',@iLINK_TABLE,1,1,3,0,0,1,'R_SPR_RASH_117_2016','COL1,COL2,COL9','NAME,CODE_STR,CODE','NNNN NNNNNNN NNN NNN',1,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Расходы', @iLINK_FORM,2, @iLINK_CODE_COL,1,'
CALC_SKELET=sql.call("dbo.RO_CALC_SKELET",m.cAlias,0x0,''0503117M'',2,''20110101'')
KEY_FOX=PADR(RTRIM(COL3),4,''0'')+PADR(RTRIM(COL4),10,''0'')+PADR(RTRIM(COL5),3,''0'')
KEY_WEB=LEFT(RTRIM(isnull(COL3,''''))+''0000'',4)+LEFT(RTRIM(ISNULL(COL4,''''))+''0000000000000'',10)+LEFT(RTRIM(ISNULL(COL5,''''))+''000'',3)
SPLIT=COL3=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,4)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',5,10)#COL5=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',15,3)
AUTO_SPR_FORM=R_SPR_RASH_117_2016
AUTO_SPR_NAME_UPD=''COL5=SUBSTRING(CODE,12,3)=000#COL4=SUBSTRING(CODE,5,10)=0000000000#COL3=SUBSTRING(CODE,1,4)=0000'', ''report_kbk'', ''CODE'', ''LONG_NAME'',''code_form=''''R_SPR_RASH_117_2016'''' and isnull(T.long_name,'''''''')=''''''''''
AUTO_SPR_CHECK= exists(select * from R_SPR_RZPR_2011 where code = SUBSTRING(T.code,1,4)) and exists(select * from dbo.R_SPR_ST_2011 where code = SUBSTRING(T.code,15,3)) and ((exists(select * from R_SPR_CSR_USER_2011 where code = SUBSTRING(T.code,5,10)) and exists(select * from dbo.R_SPR_VR_2011 where code = SUBSTRING(T.code,15,3))) OR ISNULL((SELECT Val_int FROM dbo.report_options WHERE Razdel = ''COMMON'' AND Code = ''ITOG_117''),0) =1) and T.code <> ''00000000000000000'' and not (LEFT(T.code,4) = ''9600'' and SUBSTRING(T.Code, 15,3) <> ''000'') and not (LEFT(T.code,4) = ''7900'' and SUBSTRING(T.Code, 15,3) <> ''000'')

   
AUTO_SPR_CODE_STR=case when left(T.Code,3) <> ''790'' then ''200'' else ''450'' end
AUTO_SPR_PARENT=5#left(T.Code,14) + XXX
','-1#LEFT(CODE,3)=''960''
1#LEFT(CODE,3)=''790''',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Источники финансирования дефицитов', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,2000,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,0,1,2,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Код источника финансирования дефицита бюджета по бюдж. классификации',@iLINK_TABLE,0,1,3,0,20,1,'R_SPR_IST_17_2011','COL1,COL2,COL3','LONG_NAME,CODE_STR,CODE_IST','NNNNNNNNNN NNNN NNN',NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Утвержденные бюджетные назначения',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Исполнено',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Неисполненные назначения',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Код строки и Код источника',@iLINK_TABLE,1,1,1,0,0,1,'R_SPR_IST_17_2011','COL1,COL2,COL7','LONG_NAME,CODE_STR,CODE',NULL,1,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Источники финансирования дефицитов', @iLINK_FORM,3, @iLINK_CODE_COL,1,'CALC_SKELET=sql.call("dbo.RO_CALC_SKELET",m.cAlias,0x0,''0503117M'',3,''20110101'')
KEY_FOX=PADR(RTRIM(COL2),3,''0'')+PADR(RTRIM(COL3),17,''0'')
KEY_WEB=LEFT(RTRIM(ISNULL(COL2,''''))+''000'',3)+LEFT(RTRIM(isnull(COL3,''''))+''00000000000000000000'',17)
SPLIT=COL2=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000000'',1,3)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000'',4,17)','-1#LEFT(CODE,6)=''500900''',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.3гр.6 =  т.3гр.4 -  т.3гр.5',1,1,1,'20100208','','','','0503117M','20160101','','=',3,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'т.2гр.6 =  т.2гр.4 -  т.2гр.5',1,20,1,'20110131','code <> ''79000000000000000''','','','0503117M','20160101','','=',4,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'т.1гр.6 =  т.1гр.4 -  т.1гр.5',1,1,1,'20100208','','','','0503117M','20160101','','=',3,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'т.2стр.79000000000000000гр.5 =  т.1стр.85000000000000000гр.5 -  т.2стр.96000000000000000гр.5',1,111,1,'20100208','','','','0503117M','20160101','','=',1,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'т.2стр.96000000000000000 =  т.2Фильтр:ВР 000',1,104,1,'20160208','','','','0503117M','20160101','','=',0,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.2стр.79000000000000000гр.6 =  0',0,0,1,'20110120','','','','0503117M','20160101','','=',1,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.2стр.79000000000000000гр.5 =  0 -  т.3стр.50090000000000000000гр.5',0,0,1,'20100208','','','','0503117M','20160101','','=',1,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'т.1гр.4Фильтр:Подитоги по регион. кодам =  т.1гр.4Фильтр:Региональные кода',1,0,1,'20111130','CODE NOT LIKE ''20204034______151''','','','0503117M','20160101','','=',0,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'т.1гр.5Фильтр:Подитоги по регион. кодам =  т.1гр.5Фильтр:Региональные кода',1,0,1,'20111130','CODE NOT LIKE ''20204034______151''','','','0503117M','20160101','','=',0,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'т.3стр.70001050000000000000 =  т.3стр.71001050000000000500 +  т.3стр.72001050000000000600 Дипазон колонок:5,6',1,102,0,'20110407','','5,6','','0503117M','20160101','Владивосток','=',2,'','')
INSERT #A VALUES(11,NULL,0,NULL,11,7,0,0,0,'т.1гр.5Фильтр:Подитоги по регион. кодам =  т.1гр.5Фильтр:Региональные кода',1,0,0,'20101112','','','','0503117M','20160101','ПСКОВ','=',0,'','')
INSERT #A VALUES(12,NULL,0,NULL,12,7,0,0,0,'т.1гр.4Фильтр:Подитоги по регион. кодам =  т.1гр.4Фильтр:Региональные кода',1,0,0,'20101112','','','','0503117M','20160101','ПСКОВ','=',0,'','')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'т.3стр.70001000000000000000 =  т.3стр.70001050000000000000 +  т.3стр.70001060000000000000',1,103,0,'20110407','','','','0503117M','20160101','Владивосток','=',2,'','')
INSERT #A VALUES(14,NULL,0,NULL,14,7,0,0,0,'т.3стр.50090000000000000000 =  т.3стр.70001000000000000000 +  т.3стр.52001000000000000000 +  т.3стр.62002000000000000000',1,104,0,'20110407','','','','0503117M','20160101','Владивосток','=',2,'','')
INSERT #A VALUES(15,NULL,0,NULL,15,7,0,0,0,'т.1гр.4Фильтр:Подитоги по регион. кодам =  т.1гр.4Фильтр:Региональные кода',1,0,0,'20110324','','','','0503117M','20160101','Хабаровск','=',0,'','')
INSERT #A VALUES(16,NULL,0,NULL,16,7,0,0,0,'т.3стр.70001050000000000000 =  т.3стр.71001050000000000500 +  т.3стр.72001050000000000600 Дипазон колонок:5,6',1,102,0,'20110407','','5,6','','0503117M','20160101','Владимир','=',2,'','')
INSERT #A VALUES(17,NULL,0,NULL,17,7,0,0,0,'т.3стр.70001050000000000000 =  т.3стр.71001050000000000500 +  т.3стр.72001050000000000600 Дипазон колонок:4',0,9,0,'20120319','','4','','0503117M','20160101','Владимир','=',2,'','')
INSERT #A VALUES(18,NULL,0,NULL,18,7,0,0,0,'т.3стр.70001000000000000000 =  т.3стр.70001050000000000000 +  т.3стр.70001060000000000000',1,103,0,'20110407','','','','0503117M','20160101','Владимир','=',2,'','')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'т.3стр.50090000000000000000 =  т.3стр.70001000000000000000 +  т.3стр.52001000000000000000 +  т.3стр.62002000000000000000',1,104,0,'20110407','','','','0503117M','20160101','Владимир','=',2,'','')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'т.1гр.4Фильтр:Подитоги по регион. кодам =  т.1гр.4Фильтр:Региональные кода',1,0,0,'20110608','1=0','','','0503117M','20160101','АмурскаяОбл','=',0,'','')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'т.1гр.5Фильтр:Подитоги по регион. кодам =  т.1гр.5Фильтр:Региональные кода',1,0,0,'20110608','1=0','','','0503117M','20160101','АмурскаяОбл','=',0,'','')
INSERT #A VALUES(22,NULL,0,NULL,22,7,0,0,0,'т.1гр.4Фильтр:Подитоги по регион. кодам =  т.1гр.4Фильтр:Региональные кода',1,0,0,'20110622','1=0','','','0503117M','20160101','Пенза','=',0,'','')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'т.1гр.5Фильтр:Подитоги по регион. кодам =  т.1гр.5Фильтр:Региональные кода',1,0,0,'20110622','1=0','','','0503117M','20160101','Пенза','=',0,'','')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'т.2Фильтр:ЭКР 000 =  т.2Фильтр:Не итоговыеЭКР',1,4,0,'20111121','','','','0503117M','20160101','Екатеринбург','=',0,'','')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'т.2Фильтр:ЭКР 210 =  т.2Фильтр:ЭКР 211 +  т.2Фильтр:ЭКР 212 +  т.2Фильтр:ЭКР 213',1,2,0,'20111121','1=0','','','0503117M','20160101','Екатеринбург','=',0,'','')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'т.2Фильтр:ЭКР 220 =  т.2Фильтр:ЭКР 221 +  т.2Фильтр:ЭКР 222 +  т.2Фильтр:ЭКР 223 +  т.2Фильтр:ЭКР 224 +  т.2Фильтр:ЭКР 225 +  т.2Фильтр:ЭКР 226',1,2,0,'20111121','1=0','','','0503117M','20160101','Екатеринбург','=',0,'','')
INSERT #A VALUES(27,NULL,0,NULL,27,7,0,0,0,'т.2Фильтр:ЭКР 230 =  т.2Фильтр:ЭКР 231 +  т.2Фильтр:ЭКР 232',1,2,0,'20111121','1=0','','','0503117M','20160101','Екатеринбург','=',0,'','')
INSERT #A VALUES(28,NULL,0,NULL,28,7,0,0,0,'т.2Фильтр:ЭКР 250 =  т.2Фильтр:ЭКР 251 +  т.2Фильтр:ЭКР 252 +  т.2Фильтр:ЭКР 253',1,2,0,'20111121','1=0','','','0503117M','20160101','Екатеринбург','=',0,'','')
INSERT #A VALUES(29,NULL,0,NULL,29,7,0,0,0,'т.2Фильтр:ЭКР 260 =  т.2Фильтр:ЭКР 261 +  т.2Фильтр:ЭКР 262 +  т.2Фильтр:ЭКР 263',1,2,0,'20111121','1=0','','','0503117M','20160101','Екатеринбург','=',0,'','')
INSERT #A VALUES(30,NULL,0,NULL,30,7,0,0,0,'т.2Фильтр:ЭКР 300 =  т.2Фильтр:ЭКР  310 +  т.2Фильтр:ЭКР 320 +  т.2Фильтр:ЭКР 340 +  т.2Фильтр:ЭКР 330',1,2,0,'20111121','1=0','','','0503117M','20160101','Екатеринбург','=',0,'','')
INSERT #A VALUES(31,NULL,0,NULL,31,7,0,0,0,'т.2Фильтр:ЭКР 500 =  т.2Фильтр:ЭКР  540 +  т.2Фильтр:ЭКР  530',1,2,0,'20111121','1=0','','','0503117M','20160101','Екатеринбург','=',0,'','')
INSERT #A VALUES(32,NULL,0,NULL,32,7,0,0,0,'т.2Фильтр:ЭКР 600 =  т.2Фильтр:ЭКР 620 +  т.2Фильтр:ЭКР  640',1,2,0,'20111121','1=0','','','0503117M','20160101','Екатеринбург','=',0,'','')
INSERT #A VALUES(33,NULL,0,NULL,33,7,0,0,0,'т.2стр.96000000000000000 =  т.2Фильтр:не итоговые ЭКР',1,5,0,'20111121','','','','0503117M','20160101','Екатеринбург','=',0,'','')
INSERT #A VALUES(34,NULL,0,NULL,34,7,0,0,0,'т.2Фильтр:ЭКР  240 =  т.2Фильтр:ЭКР 241 +  т.2Фильтр:ЭКР 242',1,2,0,'20111122','1=0','','','0503117M','20160101','Екатеринбург','=',0,'','')
INSERT #A VALUES(35,NULL,0,NULL,35,7,0,0,0,'т.3стр.50090000000000000000 =  т.3стр.70001000000000000000 +  т.3стр.52001000000000000000 +  т.3стр.62002000000000000000 +  т.3стр.80004000000000000000',1,104,0,'20121001','','','','0503117M','20160101','Екатеринбург','=',2,'','')
INSERT #A VALUES(36,NULL,0,NULL,36,7,0,0,0,'т.3стр.70001000000000000000 =  т.3стр.70001050000000000000 +  т.3стр.70001060000000000000',1,103,0,'20120128','','','','0503117M','20160101','Екатеринбург','=',2,'','')
INSERT #A VALUES(37,NULL,0,NULL,37,7,0,0,0,'т.3стр.70001050000000000000 =  т.3стр.71001050000000000500 +  т.3стр.72001050000000000600 Дипазон колонок:5,6',1,102,0,'20120128','','5,6','','0503117M','20160101','Екатеринбург','=',2,'','')
INSERT #A VALUES(38,NULL,0,NULL,38,7,0,0,0,'т.1гр.5Фильтр:Подитоги по регион. кодам =  т.1гр.5Фильтр:Региональные кода',1,0,0,'20120411','CODE NOT LIKE ''20204034______151'' and SUBSTRING(CODE,1,10) <> ''1169002002''','','','0503117M','20160101','Иваново','=',0,'','')
INSERT #A VALUES(39,NULL,0,NULL,39,7,0,0,0,'т.1гр.4Фильтр:Подитоги по регион. кодам =  т.1гр.4Фильтр:Региональные кода',1,0,0,'20120411','CODE NOT LIKE ''20204034______151'' and SUBSTRING(CODE,1,10) <> ''1169002002''','','','0503117M','20160101','Иваново','=',0,'','')
INSERT #A VALUES(40,NULL,0,NULL,40,7,0,0,0,'т.3Фильтр:Подитоги по регион. кодам =  т.3Фильтр:Региональные кода Дипазон колонок:4,5',1,0,1,'20120614','','4,5','','0503117M','20160101','','=',0,'','')
INSERT #A VALUES(41,NULL,0,NULL,41,7,0,0,0,'т.3Фильтр:Подитоги по регион. кодам =  т.3Фильтр:Региональные кода Дипазон колонок:4',1,0,0,'20121115','CODE not like ''5200106100202____550''','4','','0503117M','20160101','Екатеринбург','=',0,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 41
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','7','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','85000000000000000','','','','','','5','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','96000000000000000','','','','','','7','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','96000000000000000','','','','','','','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','00000000000000000200','RIGHT(RTRIM(CODE),3)=''000''','ВР 000','','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','8','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','7','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','50090000000000000000','','','','','','5','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0)','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0)','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0)','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','5','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0)','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','5','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001050000000000000','','','','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','71001050000000000500','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','72001050000000000600','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics RD1 where  RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and  float_val <> 0 and RD1.Link_COL = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'')','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','5','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and isnull(COL(5),0) <> 0','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','5','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and float_val <> 0 and RD1.Link_COL = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'')','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and isnull(COL(4),0) <> 0','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001000000000000000','','','','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001050000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001060000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','50090000000000000000','','','','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001000000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','52001000000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,4,3,'+',NULL,NULL,NULL,NULL,0,0,'','','62002000000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val <> 0)','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and col(4) <> 0','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001050000000000000','','','','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','71001050000000000500','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','72001050000000000600','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001050000000000000','','','','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','71001050000000000500','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','72001050000000000600','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001000000000000000','','','','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001050000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001060000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','50090000000000000000','','','','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001000000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','52001000000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,4,3,'+',NULL,NULL,NULL,NULL,0,0,'','','62002000000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and float_val <> 0 and RD1.Link_COL = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'')','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and isnull(COL(4),0) <> 0','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics RD1 where  RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and  float_val <> 0 and RD1.Link_COL = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'')','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','5','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and isnull(COL(5),0) <> 0','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','5','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col in (select Link_Col from report_coloumns C5 where C5.Link_Table = (select top 1 B5.Link_Table from report_coloumns B5 where B5.Link_Col = B.Link_Col)) and substring(RD1.Code_Row,11,4) <> ''0000'')','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000''','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col in (select Link_Col from report_coloumns C5 where C5.Link_Table = (select top 1 B5.Link_Table from report_coloumns B5 where B5.Link_Col = B.Link_Col)) and substring(RD1.Code_Row,11,4) <> ''0000'')','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','5','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000''','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','5','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','500','RIGHT(RTRIM(CODE),3)=''000'' AND LEFT(CODE,1)  < ''7''  and SUBSTRING(CODE,12,3)<>''000''','ЭКР 000','LEFT(code,14)+''000''','','','','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','540','right(rtrim(code),3) not in (''200'',''000'',''210'',''220'',''230'',''240'',''250'',''260'',''300'',''500'',''600'' )','Не итоговыеЭКР','LEFT(code,14)+''000''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','210','RIGHT(RTRIM(CODE),3)=''210''','ЭКР 210','LEFT(code,14)+''210''','','','','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','211','RIGHT(RTRIM(CODE),3)=''211''','ЭКР 211','LEFT(code,14)+''210''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','212','RIGHT(RTRIM(CODE),3)=''212''','ЭКР 212','LEFT(code,14)+''210''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,4,4,'+',NULL,NULL,NULL,NULL,0,0,'','','213','RIGHT(RTRIM(CODE),3)=''213''','ЭКР 213','LEFT(code,14)+''210''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','220','RIGHT(RTRIM(CODE),3)=''220''','ЭКР 220','LEFT(code,14)+''220''','','','','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','221','RIGHT(RTRIM(CODE),3)=''221''','ЭКР 221','LEFT(code,14)+''220''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','222','RIGHT(RTRIM(CODE),3)=''222''','ЭКР 222','LEFT(code,14)+''220''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,4,4,'+',NULL,NULL,NULL,NULL,0,0,'','','223','RIGHT(RTRIM(CODE),3)=''223''','ЭКР 223','LEFT(code,14)+''220''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,5,4,'+',NULL,NULL,NULL,NULL,0,0,'','','224','RIGHT(RTRIM(CODE),3)=''224''','ЭКР 224','LEFT(code,14)+''220''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,6,4,'+',NULL,NULL,NULL,NULL,0,0,'','','225','RIGHT(RTRIM(CODE),3)=''225''','ЭКР 225','LEFT(code,14)+''220''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,7,4,'+',NULL,NULL,NULL,NULL,0,0,'','','226','RIGHT(RTRIM(CODE),3)=''226''','ЭКР 226','LEFT(code,14)+''220''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','230','RIGHT(RTRIM(CODE),3)=''230''','ЭКР 230','LEFT(code,14)+''230''','','','','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','231','RIGHT(RTRIM(CODE),3)=''231''','ЭКР 231','LEFT(code,14)+''230''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','232','RIGHT(RTRIM(CODE),3)=''232''','ЭКР 232','LEFT(code,14)+''230''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','250','RIGHT(RTRIM(CODE),3)=''250''','ЭКР 250','LEFT(code,14)+''250''','','','','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','251','RIGHT(RTRIM(CODE),3)=''251''','ЭКР 251','LEFT(code,14)+''250''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','252','RIGHT(RTRIM(CODE),3)=''252''','ЭКР 252','LEFT(code,14)+''250''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,4,4,'+',NULL,NULL,NULL,NULL,0,0,'','','253','RIGHT(RTRIM(CODE),3)=''253''','ЭКР 253','LEFT(code,14)+''250''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','260','RIGHT(RTRIM(CODE),3)=''260''','ЭКР 260','LEFT(code,14)+''260''','','','','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','261','RIGHT(RTRIM(CODE),3)=''261''','ЭКР 261','LEFT(code,14)+''260''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','262','RIGHT(RTRIM(CODE),3)=''262''','ЭКР 262','LEFT(code,14)+''260''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,4,4,'+',NULL,NULL,NULL,NULL,0,0,'','','263','RIGHT(RTRIM(CODE),3)=''263''','ЭКР 263','LEFT(code,14)+''260''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','300','RIGHT(RTRIM(CODE),3)=''300''','ЭКР 300','LEFT(code,14)+''300''','','','','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','310','RIGHT(RTRIM(CODE),3)=''310''','ЭКР  310','LEFT(code,14)+''300''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','320','RIGHT(RTRIM(CODE),3)=''320''','ЭКР 320','LEFT(code,14)+''300''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,4,4,'+',NULL,NULL,NULL,NULL,0,0,'','','340','RIGHT(RTRIM(CODE),3)=''340''','ЭКР 340','LEFT(code,14)+''300''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,5,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','RIGHT(RTRIM(CODE),3)=''330''','ЭКР 330','LEFT(code,14)+''300''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','500','RIGHT(RTRIM(CODE),3)=''500''','ЭКР 500','LEFT(code,14)+''500''','','','','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','540','RIGHT(RTRIM(CODE),3)=''540''','ЭКР  540','LEFT(code,14)+''500''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','530','RIGHT(RTRIM(CODE),3)=''530''','ЭКР  530','LEFT(code,14)+''500''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','600','RIGHT(RTRIM(CODE),3)=''600''','ЭКР 600','LEFT(code,14)+''600''','','','','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','620','RIGHT(RTRIM(CODE),3)=''620''','ЭКР 620','LEFT(code,14)+''600''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','640','RIGHT(RTRIM(CODE),3)=''640''','ЭКР  640','LEFT(code,14)+''600''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','96000000000000000','','','','','','','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','00000000000000000200','right(rtrim(code),3) not in (''200'',''000'',''210'',''220'',''230'',''240'',''250'',''260'',''300'',''500'',''600'' )','не итоговые ЭКР','','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','240','RIGHT(RTRIM(CODE),3)=''240''','ЭКР  240','LEFT(code,14)+''240''','','','','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','241','RIGHT(RTRIM(CODE),3)=''241''','ЭКР 241','LEFT(code,14)+''240''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','242','RIGHT(RTRIM(CODE),3)=''242''','ЭКР 242','LEFT(code,14)+''240''','','','','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','50090000000000000000','','','','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001000000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','52001000000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,4,3,'+',NULL,NULL,NULL,NULL,0,0,'','','62002000000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,5,3,'+',NULL,NULL,NULL,NULL,0,0,'','','80004000000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001000000000000000','','','','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001050000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001060000000000000','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','70001050000000000000','','','','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','71001050000000000500','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','72001050000000000600','','','','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0)','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','5','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0)','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','5','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0)','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0)','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,14,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,13) = LEFT(CODE,13) and SUBSTRING(RD1.Code_Row,18,3) = SUBSTRING(CODE,18,3) and RD1.Link_Col in (select Link_Col from report_coloumns C5 where C5.Link_Table = (select top 1 B5.Link_Table from report_coloumns B5 where B5.Link_Col = B.Link_Col)) and substring(RD1.Code_Row,14,4) <> ''0000'')','Подитоги по регион. кодам','LEFT(CODE,13)+''0000'' + RIGHT(RTRIM(CODE),3)','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,14,4)<>''0000''','Региональные кода','LEFT(CODE,13)+''0000'' + RIGHT(RTRIM(CODE),3)','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,14,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,13) = LEFT(CODE,13) and SUBSTRING(RD1.Code_Row,18,3) = SUBSTRING(CODE,18,3) and RD1.Link_Col in (select Link_Col from report_coloumns C5 where C5.Link_Table = (select top 1 B5.Link_Table from report_coloumns B5 where B5.Link_Col = B.Link_Col)) and substring(RD1.Code_Row,14,4) <> ''0000'')','Подитоги по регион. кодам','LEFT(CODE,13)+''0000'' + RIGHT(RTRIM(CODE),3)','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,14,4)<>''0000''','Региональные кода','LEFT(CODE,13)+''0000'' + RIGHT(RTRIM(CODE),3)','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 119
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '999999    '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'999999','формы отчетности',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2016-02-08 16:52:53.407',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 = '2016-02-08 16:52:53.407'
	BEGIN
		SELECT @vcMessage = 'Форма 0503117M с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503117M с версией от ' + @vcMessage + ' не может быть обновлена версией от 2016-02-08 16:52:53.407. Обновление отклонено.'
	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

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

GO

/*

	c Кейсистемс (Keysystems), 2010
	Печать форм 127 (для параметра "все атрибуты в один отчет)
	Печать с подитогами
*/


CREATE       PROCEDURE dbo.RO_PRINT_117_ITOG_16
	@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
declare @varKSiParam int, -- 0 - без подитогов, 1 бит - подитоги по ЭКР, 2 бит - подитоги по ВР, 3 бит - подитоги по ЦСР, 4 бит - подитоги по подразделу, 5 бит - подитоги по раздеру, 6 бит - подитоги по администратору
		@varKSiNoItog int, @varKSiNoItogRash TINYINT, @cRunStr1 VARCHAR(8000)

set @varKSiParam = 0
SET @varKSiNoItogRash = 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'
   select @varKSiNoItogRash = convert(int, Value) from #Param_Print where Param = 'NoItog_Rash'   
end
if isnull(@varKSiNoItog,0) = 1 AND ISNULL(@varKSiParam, 0) = 0
begin
	exec dbo.RO_PRINT_NO_ITOG @LSF, @bDeleteEmptyRows, @data, @notNullCol, @AtrInOnePage, @WEB_excel
	return
end



IF @LSF is NULL
	return -1

declare @iLF int, @iLT int, @iYear INT, @ddate DATETIME
select @iLF = Link_Form, @iYear =YEAR(begin_date),@ddate = Begin_Date  from report_saved_forms where Link_Saved_Form = @LSF

if isnull(@WEB_excel, 0) <> 1
	select '' col1 

-- таблица доходы
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(2000), Col2 varchar(2000), Col3 varchar(2000), Col4 float, Col5 float, Col6 float)
create table #doh2 (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(2000), Col3 varchar(2000), Col4 float, Col5 float, Col6 float)

insert #doh (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6)
exec dbo.rn_get_all_adm_table 	@LSF, 1, @bDeleteEmptyRows, @AtrInOnePage, 1
select @iLT = Link_Table from report_tables where Link_Form = @iLF and orders = 1

if @varKSiParam & 16 = 16 -- подитоги по администратору
BEGIN
   if @iYear >= 2011
	   insert #doh (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6)
	   select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(D.Code,3) + '00000000000000000', SPR.Name, max(Col2), left(Col3,3) + '00000000000000000',  sum(Col4), sum(Col5), sum(col6)
	   from #doh D left join dbo.[R_SPR_ADM_2011] SPR on left(D.Code,3) = SPR.Code
	   where substring(D.code,4,1) <> '0' and substring(D.code,5,16) = '0000000000000000'
	   AND SPR.begin_date<=@ddate AND SPR.end_date >= @ddate
	   group by left(D.Code,3) + '00000000000000000', SPR.Name, left(Col3,3) + '00000000000000000'
   else
	   insert #doh (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6)
	   select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(D.Code,3) + '00000000000000000', SPR.Name, max(Col2), left(Col3,3) + '00000000000000000',  sum(Col4), sum(Col5), sum(col6)
	   from #doh D left join dbo.[RN_VIEW_ADM_2010] SPR on left(D.Code,3) = SPR.Code
	   where substring(D.code,4,1) <> '0' and substring(D.code,5,16) = '0000000000000000'
	   group by left(D.Code,3) + '00000000000000000', SPR.Name, left(Col3,3) + '00000000000000000'
end


set @cRunStr1 = '
      insert #doh2
      select * from #doh D' + case when @varKSiNoItog = 1 then ' where RIGHT(RTRIM(Code),17) not in (select RIGHT(RTRIM(CD),17) from dbo.RO_SELECT_FORM_TOTALS_DOH_20(0,' + LTRIM(STR(@iLF)) + ',1) where link_table=' + LTRIM(STR(@iLT)) + ') and RIGHT(RTRIM(Code),17) not in (select RIGHT(RTRIM(CD),17) from dbo.RA_SELECT_FORM_TOTALS(0,' + LTRIM(STR(@iLF)) + ',1) where link_table=' + LTRIM(STR(@iLT)) + ')
	   and not(SUBSTRING(D.CODE,14,4) = ''0000'' and exists(select top 1 * from #doh D2 where LEFT(D.Code,13) = LEFT(D2.Code,13) and SUBSTRING(D2.CODE,14,4) <> ''0000''))
	   or code like ''%85000000000000000%''' else '' END + ' order by left(code, 3), orders, Code'

EXEC (@cRunStr1)


declare @cStr VARCHAR(254), @region VARCHAR(250) 
exec X_GET_OPTION 'OBJ_FTP_REGION',0,@cStr output 	
set @region=rtrim(isnull(@cstr,''))

-- группируем итоги 000XXXX
IF upper(@region) = 'КИРОВ'
   SELECT 0 as checked, 0 as Upd, 0 as del, 0 as link_saved_form, 0 as link_row, MAX(orders) as orders, 0 as Calc_orders, 0 as Print_NULL, 
   CASE WHEN B.Code IS NULL THEN 
	   '000'+RIGHT(RTRIM(A.code),17) ELSE A.code END AS code, 
	   max(Col1) AS col1 , max(Col2) AS col2 , 
   CASE WHEN B.Code IS NULL THEN 
	   '000'+RIGHT(RTRIM(A.code),17) ELSE A.code END	   
	    AS col3, sum(Col4) AS col4,SUM(Col5) AS col5, sum(Col6) AS col6 
   FROM #doh2 A  
   LEFT JOIN 
   (SELECT CODE FROM #doh2 D
    WHERE RIGHT(RTRIM(Code),17) not in (select RIGHT(RTRIM(CD),17) from dbo.RO_SELECT_FORM_TOTALS_DOH_20(0,@iLF,1) where link_table=@iLT) and RIGHT(RTRIM(Code),17) 
    not in (select RIGHT(RTRIM(CD),17) from dbo.RA_SELECT_FORM_TOTALS(0,@iLF,1) where link_table=@iLT)
	      and not(SUBSTRING(D.CODE,14,4) = '0000' and exists(select top 1 * from #doh D2 where LEFT(D.Code,13) = LEFT(D2.Code,13) and SUBSTRING(D2.CODE,14,4) <> '0000'))
	      or code like '%85000000000000000%') B ON A.code = B.code 
   GROUP BY
   CASE WHEN B.Code IS NULL THEN 
	   '000'+RIGHT(RTRIM(A.code),17) ELSE A.code END 
ELSE 
   SELECT * FROM #doh2	
   
--select * from #doh order by left(code, 3), orders, Code
drop table #doh
drop table #doh2

------------------------------------------------------------------------------------------------
--- ТАБЛИЦА РАСХОДЫ С ПОДИТОГАМИ
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 float, Col7 float, Col8 float, Col9  varchar(50))
create table #rash2 (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 float, Col7 float, Col8 float, Col9 varchar(50))

select * into #rash_itog from #rash

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)
exec dbo.rn_get_all_adm_table 	@LSF, 2, @bDeleteEmptyRows, @AtrInOnePage, 1

IF @varKSiNoItogRash = 1 OR @varKSiNoItog = 1
BEGIN
   DELETE #rash
   WHERE RIGHT(RTRIM(CODE),3) IN ('200', '210', '220', '230', '240','250', '260', '300', '500', '600')

   IF @varKSiParam = 0
   BEGIN
      DELETE #rash
      WHERE RIGHT(RTRIM(CODE),3) IN ('000') AND LEFT(code,7) NOT IN ('0009600', '0007900')
   END 

   IF @varKSiParam & 2 = 0 -- удаляем подитоги по целевой статье
   BEGIN
      DELETE #rash
      WHERE RIGHT(RTRIM(CODE),6) IN ('000000') AND LEFT(code,7) NOT IN ('0009600', '0007900') AND SUBSTRING(code,8,7) <> '0000000'
   END          
   
   IF @varKSiParam & 4 = 0 -- удаляем подитоги по подразделу
   BEGIN
      DELETE #rash
      WHERE RIGHT(RTRIM(CODE),13) IN ('0000000000000') AND LEFT(code,7) NOT IN ('0009600', '0007900') AND SUBSTRING(code,6,2) <> '00'
   END          

   IF @varKSiParam & 8 = 0 -- удаляем подитоги по разделу
   BEGIN
      DELETE #rash
      WHERE RIGHT(RTRIM(CODE),15) IN ('000000000000000') AND LEFT(code,7) NOT IN ('0009600', '0007900')
   END          
END    

---------------------------------------------
/*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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,14) + '000000', '', max(Col2),max(Col3), max(Col4), '000', sum(Col6), sum(Col7), sum(Col8),left(Col9,14) + '000000'
	from #rash
	where COL6 NOT IN ('000','200', '210', '220', '230', '240','250', '260', '300', '500', '600')
	group by left(Code,14) + '000000', left(Col9,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,7) + '0000000000000', '', max(Col2),max(Col3), '0000000', '000', sum(Col6), sum(Col7), sum(Col8), left(col9,7) + '0000000000000'
	from #rash
	where COL6 NOT IN ('000','200', '210', '220', '230', '240','250', '260', '300', '500', '600')
	group by left(Code,7) + '0000000000000', left(col9,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,5) + '000000000000000', '', max(Col2),left(col3,2) + '00', '0000000', '000', sum(Col6), sum(Col7), sum(Col8), left(col9,5) + '000000000000000'
	from #rash
	where COL6 NOT IN ('000','200', '210', '220', '230', '240','250', '260', '300', '500', '600')
	group by left(Code,5) + '000000000000000', left(Col9,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,3) + '00000000000000000', '', max(Col2),'000', '0000000', '000', sum(Col6), sum(Col7), sum(Col8), left(col9,3) + '00000000000000000'
	from #rash
	where COL6 NOT IN ('000','200', '210', '220', '230', '240','250', '260', '300', '500', '600')
	group by left(Code,3) + '00000000000000000', left(Col9,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,12) + '00000000', '', max(Col2),max(Col3), max(Col4), '000', sum(Col6), sum(Col7), sum(Col8), left(Col9,12) + '00000000'
	from #rash
	where COL6 NOT IN ('000','200', '210', '220', '230', '240','250', '260', '300', '500', '600')
	group by left(Code,12) + '00000000', left(Col9,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,10) + '0000000000', '', max(Col2),max(Col3), max(Col4), '000', sum(Col6), sum(Col7), sum(Col8), left(Col9,10) + '0000000000'
	from #rash
	where COL6 NOT IN ('000','200', '210', '220', '230', '240','250', '260', '300', '500', '600')
	group by left(Code,10) + '0000000000', left(Col9,10) + '0000000000'
END

if @iYear >= 2011
   exec ro_get_name_spr @iLT, 'COL5=SUBSTRING(CODE,15,3)=000#COL4=SUBSTRING(CODE,8,7)=0000000#COL3=SUBSTRING(CODE,4,4)=0000#R_SPR_ADM_2011=LEFT(CODE,3)=000', '#rash_itog', @varKScNameCode = 'CODE', @varKScNameName = 'COL1', @varKSiLSF = @LSF
else
   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_ADM_2010=LEFT(CODE,3)=000', '#rash_itog', @varKScNameCode = 'CODE', @varKScNameName = 'COL1', @varKSiLSF = @LSF
   
UPDATE #rash
SET COL1 = ''
WHERE col6 = '000' and col5 <> '000'

if @iYear >= 2011
   exec ro_get_name_spr @iLT, 'COL5=SUBSTRING(CODE,15,3)=000#COL4=SUBSTRING(CODE,8,7)=0000000#COL3=SUBSTRING(CODE,4,4)=0000#R_SPR_ADM_2011=LEFT(CODE,3)=000', '#rash', @varKScNameCode = 'CODE', @varKScNameName = 'COL1', @varKSiLSF = @LSF
else
   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_ADM_2010=LEFT(CODE,3)=000', '#rash', @varKScNameCode = 'CODE', @varKScNameName = 'COL1', @varKSiLSF = @LSF

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

if @AtrInOnePage = 1 and not exists (select top 1 * from #rash where code like '%000960000%') -- еще общий итог по администраторма
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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, '00096000000000000000', 'Расходы - всего', '200','9600', '0000000', '000', sum(Col6), sum(Col7), sum(Col8), '00096000000000000000'
	from #rash
	where COL6 NOT IN ('000','200', '210', '220', '230', '240','250', '260', '300', '500', '600')
end

IF upper(@region) = 'КИРОВ'
   BEGIN
      INSERT #RASH2 (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9)  
      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 from #rash_itog
      union
      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 from #rash R where not exists(select top 1 * from #rash_itog R1 where R.code = R1.code)

      SELECT 0 as checked, 0 as Upd, 0 as del, 0 as link_saved_form, 0 as link_row, MAX(orders) as orders, 0 as Calc_orders, 0 as Print_NULL,
         CASE WHEN B.Code IS NOT NULL THEN 
	         '000'+RIGHT(RTRIM(A.code),17) ELSE A.code END AS code,
	         MAX(col1) AS col1 ,MAX(col2) AS col2 ,MAX(col3) AS col3,MAX(col4) AS col4,MAX(col5) AS col5 ,SUM(col6) AS col6,
	         SUM(col7) AS col7,SUM(col8) AS col8,
	         CASE WHEN B.Code IS NOT NULL THEN 
	         '000'+RIGHT(RTRIM(A.code),17) ELSE A.code END AS col9
       FROM #rash2 A
      LEFT JOIN (SELECT CODE FROM #rash2     
      WHERE 
      (RIGHT(RTRIM(CODE),3) IN ('200', '210', '220', '230', '240','250', '260', '300', '500', '600'))
      OR (RIGHT(RTRIM(CODE),3) IN ('000') AND LEFT(code,7) NOT IN ('0009600', '0007900'))
      OR (RIGHT(RTRIM(CODE),6) IN ('000000') AND LEFT(code,7) NOT IN ('0009600', '0007900') AND SUBSTRING(code,8,7) <> '0000000')
      OR (RIGHT(RTRIM(CODE),13) IN ('0000000000000') AND LEFT(code,7) NOT IN ('0009600', '0007900') AND SUBSTRING(code,6,2) <> '00')
      OR (RIGHT(RTRIM(CODE),15) IN ('000000000000000') AND LEFT(code,7) NOT IN ('0009600', '0007900'))) B ON A.CODE = B.CODE 
      GROUP BY    CASE WHEN B.Code IS NOT NULL THEN 
	         '000'+RIGHT(RTRIM(A.code),17) ELSE A.code END
	END         
ELSE
	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 from #rash_itog
   union
   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 from #rash R where not exists(select top 1 * from #rash_itog R1 where R.code = R1.code)


drop table #rash_itog
drop table #rash
-------------------------------------------------------------------------------------------------

-- таблица источники
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(1000), Col2 varchar(1000), Col3 varchar(1000), Col4 float, Col5 float, Col6 float, Col7 varchar(1000))
create table #ist2 (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 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)
exec dbo.rn_get_all_adm_table 	@LSF, 3, @bDeleteEmptyRows, @AtrInOnePage, 1

if @varKSiParam & 16 = 16 -- подитоги по администратору
begin
   if @iYear >= 2011
	   insert #ist (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7)
	   select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(D.Code,3) + '00000000000000000000', SPR.Name, max(Col2), '00000000000000000',  sum(Col4), sum(Col5), sum(col6), left(Col7,3) + '00000000000000000000'
	   from #ist D left join dbo.[R_SPR_ADM_2011] SPR on left(D.Code,3) = SPR.Code
	   where (substring(D.code,8,1) <> '0' and substring(D.code,9,15) = '000000000000000') --or substring(D.Code,4,20) = '70001050000000000000'
	   group by left(D.Code,3) + '00000000000000000000', SPR.Name, left(Col7,3) + '00000000000000000000'
   else
	   insert #ist (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7)
	   select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(D.Code,3) + '00000000000000000000', SPR.Name, max(Col2), '00000000000000000',  sum(Col4), sum(Col5), sum(col6), left(Col7,3) + '00000000000000000000'
	   from #ist D left join dbo.[RN_VIEW_ADM_2010] SPR on left(D.Code,3) = SPR.Code
	   where (substring(D.code,8,1) <> '0' and substring(D.code,9,15) = '000000000000000') --or substring(D.Code,4,20) = '70001050000000000000'
	   group by left(D.Code,3) + '00000000000000000000', SPR.Name, left(Col7,3) + '00000000000000000000'
end

select @iLT = Link_Table from report_tables where Link_Form = @iLF and orders = 3


      set @cRunStr1 = 'insert #ist2 select * from #ist'  + case when @varKSiNoItog = 1 then ' where RIGHT(RTRIM(CODE),17) not in (select RIGHT(RTRIM(CD), 17) from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,' + LTRIM(STR(@iLF)) + ',1) where link_table=' + LTRIM(STR(@iLT)) + ')
	   or code like ''%500%90000000000000000%'' 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%''' else '' END
    + ' order by left(code, 3), orders, Code'

execute( @cRunStr1)



IF upper(@region) = 'КИРОВ'
   BEGIN
   SELECT 0 as checked, 0 as Upd, 0 as del, 0 as link_saved_form, 0 as link_row, MAX(orders) as orders, 0 as Calc_orders, 0 as Print_NULL, 
   CASE WHEN B.Code IS NULL THEN 
	   '000'+RIGHT(RTRIM(A.code),17) ELSE A.code END AS code, 
	   max(Col1) AS col1, max(Col2) AS col2, max(Col3) AS col3, sum(Col4) AS col4,SUM(Col5) AS col5, sum(Col6) AS col6, MAX(col7) AS col7 
   FROM #ist2 A  
   LEFT JOIN 
   (SELECT CODE FROM #ist2 D
    WHERE
    RIGHT(RTRIM(CODE),17) not in (select RIGHT(RTRIM(CD), 17) from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,LTRIM(STR(@iLF)),1) where link_table=@iLT)
	   or code like '%500%90000000000000000%' 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%' 
   ) B ON A.code = B.code 
   GROUP BY
   CASE WHEN B.Code IS NULL THEN 
	   '000'+RIGHT(RTRIM(A.code),17) ELSE A.code END 
   	
   END
ELSE
	SELECT * FROM #ist2   

--select * from #ist order by left(code, 3), orders, Code
drop table #ist


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.[RO_PRINT_117_ITOG_16] TO PUBLIC

GO



-- Сгенерировано х.п. RA_EXPORT_GROUP_KS. (фев  5 2016  3:52:57:440PM)
-- Выгружены следующие группы междокументных КС:
-- 2016_4 - Заполнение: 0503117M - 0503127M (25 шт.)
-- Параметры выгрузки:
-- удаление старых КС : да

SET NOCOUNT               ON
SET ANSI_NULLS            ON
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

----------------------------------------------------------------------------------------------------
-- Раздел удаления правил.

DELETE
FROM dbo.[REPORT_CONTROL_RULES]
WHERE [LINK_RULE] IN (SELECT [A].[LINK_RULE]
                      FROM dbo.[REPORT_CONTROL_GROUP] [A]
                      JOIN dbo.[REPORT_GROUP_KS]      [B] ON [A].[LINK_GROUP_KS] = [B].[LINK_GROUP_KS]
                      WHERE [B].[CODE] = '2016_4' AND
                            (SELECT COUNT(*)
                             FROM dbo.[REPORT_CONTROL_GROUP] [C]
                             WHERE [C].[LINK_RULE] = [A].[LINK_RULE]) = 1)

DELETE [B]
FROM dbo.[REPORT_GROUP_KS]      [A]
JOIN dbo.[REPORT_CONTROL_GROUP] [B] ON [A].[LINK_GROUP_KS] = [B].[LINK_GROUP_KS]
WHERE [A].[CODE] = '2016_4'

GO

----------------------------------------------------------------------------------------------------
-- Раздел сохранения правил.
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#tabRULES') IS NOT NULL
BEGIN
   DROP TABLE #tabRULES
END

CREATE TABLE #tabRULES ([LINK_RULE]       INT NULL,
                        [LINK_TASK]       INT NULL,
                        [IsOutside]       TINYINT NULL,
                        [LINK_FORM]       INT NULL,
                        [OrderRule]       INT NULL,
                        [PERIOD]          SMALLINT NULL,
                        [PERIOD_NOM]      SMALLINT NULL,
                        [ORG_LEVEL]       SMALLINT NULL,
                        [IsSvod]          SMALLINT NULL,
                        [STR_RULE]        VARCHAR (6000) NULL,
                        [IsDoschet]       TINYINT NULL,
                        [CALC_ORDERS]     INT NULL,
                        [IsSystemsRule]   TINYINT NULL ,
                        [MODIFY_DATE]     DATETIME NULL,
                        [ROWS]            VARCHAR(1000),
                        [COLS]            VARCHAR(250),
                        [ROWS_DESC]       VARCHAR (250),
                        [CODE_FORM]       VARCHAR (250),
                        [START_DATE_FORM] VARCHAR (250),
                        [REGION]			 VARCHAR (100),
                        [SIGN_SR]         CHAR(2)      NOT NULL,
                        [ALGORITHM]       TINYINT      NOT NULL,
                        [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                        [COMMENT]     VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabRULES',@iERROR)
END

GO

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (1,1,568248,7,0,0,0,'ф.0503117Mт.1гр.4 =  ф.0503127Mт.1гр.4',1,0,1,'20160201','','','','',NULL,'                                                                                                    ','=',3,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (2,1,568249,7,0,0,0,'ф.0503117Mт.1гр.5 =  ф.0503127Mт.1гр.8',1,0,1,'20160201','','','','',NULL,'                                                                                                    ','=',3,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (3,1,568250,7,0,0,0,'ф.0503117Mт.2гр.4 =  ф.0503127Mт.2гр.4',1,0,1,'20160201','','','','',NULL,'                                                                                                    ','=',3,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (4,1,568251,7,0,0,0,'ф.0503117Mт.2гр.5 =  ф.0503127Mт.2гр.9',1,0,1,'20160201','','','','',NULL,'                                                                                                    ','=',3,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (5,1,568252,7,0,0,0,'ф.0503117Mт.3гр.4 =  ф.0503127Mт.3гр.4',1,0,1,'20160201','','','','',NULL,'','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (6,1,568253,7,0,0,0,'ф.0503117Mт.3гр.5 =  ф.0503127Mт.3гр.8',1,0,1,'20160201','','','','',NULL,'','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (7,1,568254,7,0,0,0,'ф.0503117M[С]т.3стр.71001050201020000510гр.4 =  ф.0503127M[С]т.3стр.71001050201020000510гр.4 +  ф.0503127M[С]т.3стр.81106000000000000000гр.4 +  ф.0503127M[С]т.3стр.82109000000000000000гр.4',1,1,1,'20160201','','','','',NULL,'                                                                                                    ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (8,1,568255,7,0,0,0,'ф.0503117M[С]т.3стр.72001050201020000610гр.4 =  ф.0503127M[С]т.3стр.72001050201020000610гр.4 +  ф.0503127M[С]т.3стр.81207000000000000000гр.4 +  ф.0503127M[С]т.3стр.82201000000000000000гр.4',1,1,1,'20160201','','','','',NULL,'                                                                                                    ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (9,1,568256,7,0,0,0,'ф.0503117M[С]т.3стр.71001050201020000510гр.5 =  ф.0503127M[С]т.3стр.71001050201020000510гр.8 +  ф.0503127M[С]т.3стр.81106000000000000000гр.8 +  ф.0503127M[С]т.3стр.82109000000000000000гр.8',1,1,1,'20160201','','','','',NULL,'                                                                                                    ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (10,1,568257,7,0,0,0,'ф.0503117M[С]т.3стр.71001050201020000510гр.6 =  ф.0503127M[С]т.3стр.71001050201020000510гр.9 +  ф.0503127M[С]т.3стр.81106000000000000000гр.9 +  ф.0503127M[С]т.3стр.82109000000000000000гр.9',1,1,1,'20160201','','','','',NULL,'                                                                                                    ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (11,1,568258,7,0,0,0,'ф.0503117M[С]т.3стр.72001050201020000610гр.5 =  ф.0503127M[С]т.3стр.72001050201020000610гр.8 +  ф.0503127M[С]т.3стр.81207000000000000000гр.8 +  ф.0503127M[С]т.3стр.82201000000000000000гр.8',1,1,1,'20160201','','','','',NULL,'                                                                                                    ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (12,1,568259,7,0,0,0,'ф.0503117M[С]т.3стр.72001050201020000610гр.6 =  ф.0503127M[С]т.3стр.72001050201020000610гр.9 +  ф.0503127M[С]т.3стр.81207000000000000000гр.9 +  ф.0503127M[С]т.3стр.82201000000000000000гр.9',1,1,1,'20160201','','','','',NULL,'                                                                                                    ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (13,1,568260,7,0,0,0,'ф.0503117M[СП]т.3стр.71001050201100000510гр.4 =  ф.0503127M[СП]т.3стр.71001050201100000510гр.4 +  ф.0503127M[СП]т.3стр.81106000000000000000гр.4 +  ф.0503127M[СП]т.3стр.82109000000000000000гр.4',1,1,0,'20160201','','','','',NULL,'Чебоксары                                                                                           ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (14,1,568261,7,0,0,0,'ф.0503117M[СП]т.3стр.71001050201100000510гр.5 =  ф.0503127M[СП]т.3стр.71001050201100000510гр.8 +  ф.0503127M[СП]т.3стр.81106000000000000000гр.8 +  ф.0503127M[СП]т.3стр.82109000000000000000гр.8',1,1,0,'20160201','','','','',NULL,'Чебоксары                                                                                           ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (15,1,568262,7,0,0,0,'ф.0503117M[СП]т.3стр.72001050201100000610гр.4 =  ф.0503127M[СП]т.3стр.72001050201100000610гр.4 +  ф.0503127M[СП]т.3стр.81207000000000000000гр.4 +  ф.0503127M[СП]т.3стр.82201000000000000000гр.4',1,1,0,'20160201','','','','',NULL,'Чебоксары                                                                                           ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (16,1,568263,7,0,0,0,'ф.0503117M[СП]т.3стр.72001050201100000610гр.5 =  ф.0503127M[СП]т.3стр.72001050201100000610гр.8 +  ф.0503127M[СП]т.3стр.81207000000000000000гр.8 +  ф.0503127M[СП]т.3стр.82201000000000000000гр.8',1,1,0,'20160201','','','','',NULL,'Чебоксары                                                                                           ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (17,1,568264,7,0,0,0,'ф.0503117M[ГО]т.3стр.71001050201040000510гр.4 =  ф.0503127M[ГО]т.3стр.71001050201040000510гр.4 +  ф.0503127M[ГО]т.3стр.81106000000000000000гр.4 +  ф.0503127M[ГО]т.3стр.82109000000000000000гр.4',1,1,0,'20160201','','','','',NULL,'Чебоксары                                                                                           ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (18,1,568265,7,0,0,0,'ф.0503117M[ГО]т.3стр.71001050201040000510гр.5 =  ф.0503127M[ГО]т.3стр.71001050201040000510гр.8 +  ф.0503127M[ГО]т.3стр.81106000000000000000гр.8 +  ф.0503127M[ГО]т.3стр.82109000000000000000гр.8',1,1,0,'20160201','','','','',NULL,'Чебоксары                                                                                           ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (19,1,568266,7,0,0,0,'ф.0503117M[ГО]т.3стр.72001050201040000610гр.4 =  ф.0503127M[ГО]т.3стр.72001050201040000610гр.4 +  ф.0503127M[ГО]т.3стр.81207000000000000000гр.4 +  ф.0503127M[ГО]т.3стр.82201000000000000000гр.4',1,1,0,'20160201','','','','',NULL,'Чебоксары                                                                                           ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (20,1,568267,7,0,0,0,'ф.0503117M[ГО]т.3стр.72001050201040000610гр.5 =  ф.0503127M[ГО]т.3стр.72001050201040000610гр.8 +  ф.0503127M[ГО]т.3стр.81207000000000000000гр.8 +  ф.0503127M[ГО]т.3стр.82201000000000000000гр.8',1,1,0,'20160201','','','','',NULL,'Чебоксары                                                                                           ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (21,1,568268,7,0,0,0,'ф.0503117M[ГО]т.3стр.71001050201040000510гр.5 =  ф.0503127M[ГО]т.3стр.71001050201040000510гр.8 +  ф.0503127M[ГО]т.3стр.81106000000000000000гр.8 +  ф.0503127M[ГО]т.3стр.82109000000000000000гр.8',1,1,0,'20160201','','','','',NULL,'Чебоксары                                 ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (22,1,568269,7,0,0,0,'ф.0503117M[СБ]т.3стр.71001050201050000510гр.4 =  ф.0503127M[СБ]т.3стр.71001050201050000510гр.4 +  ф.0503127M[СБ]т.3стр.81106000000000000000гр.4 +  ф.0503127M[СБ]т.3стр.82109000000000000000гр.4',1,1,1,'20160201','','','','',NULL,'','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (23,1,568270,7,0,0,0,'ф.0503117M[СБ]т.3стр.71001050201050000510гр.5 =  ф.0503127M[СБ]т.3стр.71001050201050000510гр.8 +  ф.0503127M[СБ]т.3стр.81106000000000000000гр.8 +  ф.0503127M[СБ]т.3стр.82109000000000000000гр.8',1,1,1,'20160201','','','','',NULL,'','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (24,1,568271,7,0,0,0,'ф.0503117M[СБ]т.3стр.72001050201050000610гр.5 =  ф.0503127M[СБ]т.3стр.72001050201050000610гр.8 +  ф.0503127M[СБ]т.3стр.81207000000000000000гр.8 +  ф.0503127M[СБ]т.3стр.82201000000000000000гр.8',1,1,1,'20160201','','','','',NULL,'                                                                                                    ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (25,1,568272,7,0,0,0,'ф.0503117M[СБ]т.3стр.72001050201050000610гр.4 =  ф.0503127M[СБ]т.3стр.72001050201050000610гр.4 +  ф.0503127M[СБ]т.3стр.81207000000000000000гр.4 +  ф.0503127M[СБ]т.3стр.82201000000000000000гр.4',1,1,1,'20160201','','','','',NULL,'','=',1,'','')


GO

DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #tabRules) <> 25
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #tabRules',0)
END

GO

DECLARE @iERROR INT
IF OBJECT_ID('tempdb..#tabROWS') IS NOT NULL
BEGIN
   DROP TABLE #tabROWS
END

CREATE TABLE #tabROWS ([LINK_RULE]       INT NULL,
                       [OrderRow]        INT NULL,
                       [VAL_TYPE]        TINYINT NULL,
                       [SIGN]            CHAR(2) NULL,
                       [LINK_FORM]       INT NULL,
                       [LINK_TABLE]      INT NULL,
                       [LINK_COL]        INT NULL,
                       [LINK_ROW]        INT NULL,
                       [PERIOD_FORM]     SMALLINT NULL,
                       [FACTOR]          FLOAT NULL,
                       [EXEC_PROC]       VARCHAR(250) NULL,
                       [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                       [CODE_ROW]        VARCHAR(250) NULL,
                       [FILTER]          VARCHAR(1000) NULL,
                       [FILTER_DESC]     VARCHAR(250) NULL,
                       [MASKA]           VARCHAR(250) NULL,
                       [MASKA_DESC]      VARCHAR(250) NULL,
                       [PERIOD_TYPE]     TINYINT,
                       [BUDG_CODE]       CHAR(5),
                       [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                       [COL]             VARCHAR(100) NULL,
                       [ROW]             VARCHAR(100) NULL,
                       [TABLE]           VARCHAR(25)  NULL,
                       [START_DATE_FORM] DATETIME     NULL,
                       [PERIOD_YEAR]     SMALLINT     NULL,
                       [ATR_CODE]        VARCHAR(254) NOT NULL,
                       [PART]            TINYINT      NOT NULL,
                       [BEGIN_DATE]      DATETIME     NULL,
                       [PX]              FLOAT(53)    NOT NULL,
                       [PX_COMMENT]      VARCHAR(600) NOT NULL,
                       [PROPERTY]        TINYINT      DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabROWS',@iERROR)
END

GO

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (1,2,3,'+ ',0,0,'','','','','','','',8,'     ','4','','1','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (2,2,3,'+ ',0,0,'','','','','','','',8,'     ','8','','1','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (3,2,3,'+ ',0,0,'','','','','','','',8,'     ','6','','2','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (4,2,3,'+ ',0,0,'','','','','','','',8,'     ','11','','2','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (5,2,4,'+ ',0,0,'','','','SUBSTRING(CODE,4,3)<''801''','','CODE','',8,'     ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (6,2,4,'+ ',0,0,'','','','SUBSTRING(CODE,4,3)<''801''','','CODE','',8,'     ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (7,2,3,'+ ',0,0,'','','71001050201020000510','','','','',8,'С    ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (7,3,3,'+ ',0,0,'','','81106000000000000000','','','','',8,'С    ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (7,4,3,'+ ',0,0,'','','82109000000000000000','','','','',8,'С    ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (8,2,3,'+ ',0,0,'','','72001050201020000610','','','','',8,'С    ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (8,3,3,'+ ',0,0,'','','81207000000000000000','','','','',8,'С    ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (8,4,3,'+ ',0,0,'','','82201000000000000000','','','','',8,'С    ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (9,2,3,'+ ',0,0,'','','71001050201020000510','','','','',8,'С    ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (9,3,3,'+ ',0,0,'','','81106000000000000000','','','','',8,'С    ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (9,4,3,'+ ',0,0,'','','82109000000000000000','','','','',8,'С    ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (10,2,3,'+ ',0,0,'','','71001050201020000510','','','','',8,'С    ','9','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (10,3,3,'+ ',0,0,'','','81106000000000000000','','','','',8,'С    ','9','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (10,4,3,'+ ',0,0,'','','82109000000000000000','','','','',8,'С    ','9','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (11,2,3,'+ ',0,0,'','','72001050201020000610','','','','',8,'С    ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (11,3,3,'+ ',0,0,'','','81207000000000000000','','','','',8,'С    ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (11,4,3,'+ ',0,0,'','','82201000000000000000','','','','',8,'С    ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (12,2,3,'+ ',0,0,'','','72001050201020000610','','','','',8,'С    ','9','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (12,3,3,'+ ',0,0,'','','81207000000000000000','','','','',8,'С    ','9','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (12,4,3,'+ ',0,0,'','','82201000000000000000','','','','',8,'С    ','9','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (13,2,3,'+ ',0,0,'','','71001050201100000510','','','','',8,'СП   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (13,3,3,'+ ',0,0,'','','81106000000000000000','','','','',8,'СП   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (13,4,3,'+ ',0,0,'','','82109000000000000000','','','','',8,'СП   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (14,2,3,'+ ',0,0,'','','71001050201100000510','','','','',8,'СП   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (14,3,3,'+ ',0,0,'','','81106000000000000000','','','','',8,'СП   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (14,4,3,'+ ',0,0,'','','82109000000000000000','','','','',8,'СП   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (15,2,3,'+ ',0,0,'','','72001050201100000610','','','','',8,'СП   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (15,3,3,'+ ',0,0,'','','81207000000000000000','','','','',8,'СП   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (15,4,3,'+ ',0,0,'','','82201000000000000000','','','','',8,'СП   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (16,2,3,'+ ',0,0,'','','72001050201100000610','','','','',8,'СП   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (16,3,3,'+ ',0,0,'','','81207000000000000000','','','','',8,'СП   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (16,4,3,'+ ',0,0,'','','82201000000000000000','','','','',8,'СП   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (17,2,3,'+ ',0,0,'','','71001050201040000510','','','','',8,'ГО   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (17,3,3,'+ ',0,0,'','','81106000000000000000','','','','',8,'ГО   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (17,4,3,'+ ',0,0,'','','82109000000000000000','','','','',8,'ГО   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (18,2,3,'+ ',0,0,'','','71001050201040000510','','','','',8,'ГО   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (18,3,3,'+ ',0,0,'','','81106000000000000000','','','','',8,'ГО   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (18,4,3,'+ ',0,0,'','','82109000000000000000','','','','',8,'ГО   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (19,2,3,'+ ',0,0,'','','72001050201040000610','','','','',8,'ГО   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (19,3,3,'+ ',0,0,'','','81207000000000000000','','','','',8,'ГО   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (19,4,3,'+ ',0,0,'','','82201000000000000000','','','','',8,'ГО   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (20,2,3,'+ ',0,0,'','','72001050201040000610','','','','',8,'ГО   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (20,3,3,'+ ',0,0,'','','81207000000000000000','','','','',8,'ГО   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (20,4,3,'+ ',0,0,'','','82201000000000000000','','','','',8,'ГО   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (21,2,3,'+ ',0,0,'','','71001050201040000510','','','','',8,'ГО   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (21,3,3,'+ ',0,0,'','','81106000000000000000','','','','',8,'ГО   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (21,4,3,'+ ',0,0,'','','82109000000000000000','','','','',8,'ГО   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (22,2,3,'+ ',0,0,'','','71001050201050000510','','','','',8,'СБ   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (22,3,3,'+ ',0,0,'','','81106000000000000000','','','','',8,'СБ   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (22,4,3,'+ ',0,0,'','','82109000000000000000','','','','',8,'СБ   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (23,2,3,'+ ',0,0,'','','71001050201050000510','','','','',8,'СБ   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (23,3,3,'+ ',0,0,'','','81106000000000000000','','','','',8,'СБ   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (23,4,3,'+ ',0,0,'','','82109000000000000000','','','','',8,'СБ   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (24,2,3,'+ ',0,0,'','','72001050201050000610','','','','',8,'СБ   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (24,3,3,'+ ',0,0,'','','81207000000000000000','','','','',8,'СБ   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (24,4,3,'+ ',0,0,'','','82201000000000000000','','','','',8,'СБ   ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (25,2,3,'+ ',0,0,'','','72001050201050000610','','','','',8,'СБ   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (25,3,3,'+ ',0,0,'','','81207000000000000000','','','','',8,'СБ   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (25,4,3,'+ ',0,0,'','','82201000000000000000','','','','',8,'СБ   ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (1,1,3,'+ ',0,0,'','','','','','','',8,'     ','4','','1','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (2,1,3,'+ ',0,0,'','','','','','','',8,'     ','5','','1','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (3,1,3,'+ ',0,0,'','','','','','','',8,'     ','6','','2','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (4,1,3,'+ ',0,0,'','','','','','','',8,'     ','7','','2','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (5,1,4,'+ ',0,0,'','','','','','CODE#CODE','',8,'     ','4','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (8,1,3,'+ ',0,0,'','','72001050201020000610','','','','',8,'С    ','4','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (7,1,3,'+ ',0,0,'','','71001050201020000510','','','','',8,'С    ','4','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (6,1,4,'+ ',0,0,'','','','','','CODE#CODE','',8,'     ','5','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (12,1,3,'+ ',0,0,'','','72001050201020000610','','','','',8,'С    ','6','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (11,1,3,'+ ',0,0,'','','72001050201020000610','','','','',8,'С    ','5','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (10,1,3,'+ ',0,0,'','','71001050201020000510','','','','',8,'С    ','6','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (9,1,3,'+ ',0,0,'','','71001050201020000510','','','','',8,'С    ','5','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (20,1,3,'+ ',0,0,'','','72001050201040000610','','','','',8,'ГО   ','5','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (19,1,3,'+ ',0,0,'','','72001050201040000610','','','','',8,'ГО   ','4','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (18,1,3,'+ ',0,0,'','','71001050201040000510','','','','',8,'ГО   ','5','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (17,1,3,'+ ',0,0,'','','71001050201040000510','','','','',8,'ГО   ','4','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (16,1,3,'+ ',0,0,'','','72001050201100000610','','','','',8,'СП   ','5','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (15,1,3,'+ ',0,0,'','','72001050201100000610','','','','',8,'СП   ','4','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (14,1,3,'+ ',0,0,'','','71001050201100000510','','','','',8,'СП   ','5','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (13,1,3,'+ ',0,0,'','','71001050201100000510','','','','',8,'СП   ','4','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (25,1,3,'+ ',0,0,'','','72001050201050000610','','','','',8,'СБ   ','4','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (24,1,3,'+ ',0,0,'','','72001050201050000610','','','','',8,'СБ   ','5','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (23,1,3,'+ ',0,0,'','','71001050201050000510','','','','',8,'СБ   ','5','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (22,1,3,'+ ',0,0,'','','71001050201050000510','','','','',8,'СБ   ','4','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (21,1,3,'+ ',0,0,'','','71001050201040000510','','','','',8,'ГО   ','5','','3','0503117M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)


GO

DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #tabRows) <> 88
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #tabRows',0)
END

GO

DECLARE @iERROR INT
IF OBJECT_ID('tempdb..#tabGroupRules') IS NOT NULL
BEGIN
   DROP TABLE #tabGroupRules
END

CREATE TABLE #tabGroupRules ([GROUP_CODE] VARCHAR(20) NOT NULL,
                             [LINK_RULE]  INT         NOT NULL)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabGroupRules',@iERROR)
END

GO
INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (1,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (2,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (3,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (4,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (5,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (6,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (7,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (8,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (9,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (10,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (11,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (12,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (13,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (14,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (15,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (16,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (17,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (18,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (19,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (20,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (21,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (22,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (23,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (24,'2016_4')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (25,'2016_4')


GO

DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #tabGroupRules) <> 25
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #tabGroupRules',0)
END

GO

----------------------------------------------------------------------------------------------------
-- Раздел сохранения групп.
DECLARE @vcGROUP_CODE CHAR(20), @iGROUP_LINK INT, @iLINK_RULE INT

SELECT @iGROUP_LINK = [LINK] FROM dbo.[RA_VIEW_GROUP_KS] WHERE [CODE] = '2016_4'
EXEC dbo.[RA_SAVE_GROUP_KS] @iGROUP_LINK OUTPUT, '2016_4' , 'Заполнение: 0503117M - 0503127M', 2, 0, '20160101', NULL

GO

DECLARE @iERROR INT

CREATE INDEX #IX_tabROWS ON #tabROWS([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #tabRULES([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#tabRULES', '#tabROWS', 1, '#tabGroupRules'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog

COMMIT TRANSACTION -- Фиксация транзакции.
GO

exec RN_SAVE_REPORT_KBK 0,'ВР_2011',0,'Виды расходов','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='SHARED_2011' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'ВР_2011',@link_self,'Виды расходов','HEADER'
GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'000',@link_self,'Неизвестный вид расходов','ВР_2011',0,'',0,'','Неизвестный вид расходов',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'001',@link_self,'Выполнение функций бюджетными учреждениями','ВР_2011',0,'',0,'','Выполнение функций бюджетными учреждениями',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'002',@link_self,'Трансферты бюджету Фонда социального страхования Российской Федерации','ВР_2011',0,'',0,'','Трансферты бюджету Фонда социального страхования Российской Федерации',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'003',@link_self,'Бюджетные инвестиции','ВР_2011',0,'',0,'','Бюджетные инвестиции',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'004',@link_self,'Трансферты бюджету Пенсионного фонда Российской Федерации','ВР_2011',0,'',0,'','Трансферты бюджету Пенсионного фонда Российской Федерации',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'005',@link_self,'Социальные выплаты','ВР_2011',0,'',0,'','Социальные выплаты',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'006',@link_self,'Субсидии юридическим лицам','ВР_2011',0,'',0,'','Субсидии юридическим лицам',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'007',@link_self,'Прочие дотации','ВР_2011',0,'',0,'','Прочие дотации',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'008',@link_self,'Фонд финансовой поддержки','ВР_2011',0,'',0,'','Фонд финансовой поддержки',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'009',@link_self,'Фонд компенсаций','ВР_2011',0,'',0,'','Фонд компенсаций',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'010',@link_self,'Фонд софинансирования','ВР_2011',0,'',0,'','Фонд софинансирования',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'011',@link_self,'Выполнение международных обязательств','ВР_2011',0,'',0,'','Выполнение международных обязательств',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'012',@link_self,'Выполнение функций государственными органами','ВР_2011',0,'',0,'','Выполнение функций государственными органами',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'013',@link_self,'Прочие расходы','ВР_2011',0,'',0,'','Прочие расходы',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'014',@link_self,'Функционирование органов в сфере национальной безопасности, правоохранительной деятельности и обороны','ВР_2011',0,'',0,'','Функционирование органов в сфере национальной безопасности, правоохранительной деятельности и обороны',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'015',@link_self,'Научно-исследовательские и опытно-конструкторские работы','ВР_2011',0,'',0,'','Научно-исследовательские и опытно-конструкторские работы',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'016',@link_self,'Трансферты бюджету Федерального фонда обязательного медицинского страхования','ВР_2011',0,'',0,'','Трансферты бюджету Федерального фонда обязательного медицинского страхования',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'017',@link_self,'Иные межбюджетные трансферты','ВР_2011',0,'',0,'','Иные межбюджетные трансферты',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'018',@link_self,'Иные субсидии','ВР_2011',0,'',0,'','Иные субсидии',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'019',@link_self,'Субсидии некоммерческим организациям','ВР_2011',0,'',0,'','Субсидии некоммерческим организациям',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'020',@link_self,'Софинансирование объектов капитального строительства государственной собственности субъектов Российской Федерации (объектов капитального строительства собственности муниципальных образований)','ВР_2011',0,'',0,'','Софинансирование объектов капитального строительства государственной собственности субъектов Российской Федерации (объектов капитального строительства собственности муниципальных образований)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'022',@link_self,'Мероприятия в сфере образования','ВР_2011',0,'',0,'','Мероприятия в сфере образования',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'023',@link_self,'Мероприятия по поддержке и развитию культуры, искусства, кинематографии, средств массовой информации и архивного дела','ВР_2011',0,'',0,'','Мероприятия по поддержке и развитию культуры, искусства, кинематографии, средств массовой информации и архивного дела',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'026',@link_self,'Компенсация части затрат на приобретение средств химизации','ВР_2011',0,'',0,'','Компенсация части затрат на приобретение средств химизации',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'027',@link_self,'Совершенствование программного и методического обеспечения осуществления государственной радиационно-эпидемиологической регистрации граждан на федеральном и региональном уровнях и актуализация Национального регистра','ВР_2011',0,'',0,'','Совершенствование программного и методического обеспечения осуществления государственной радиационно-эпидемиологической регистрации граждан на федеральном и региональном уровнях и актуализация Национального регистра',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'028',@link_self,'Обеспечение доступности информации по проблемам преодоления последствий радиационных катастроф и инцидентов, разработка и продвижение информационных проектов по формированию адекватного восприятия гражданами возможных угроз жизнедеятельности и снижен','ВР_2011',0,'',0,'','Обеспечение доступности информации по проблемам преодоления последствий радиационных катастроф и инцидентов, разработка и продвижение информационных проектов по формированию адекватного восприятия гражданами возможных угроз жизнедеятельности и снижению уровня социально-психологической напряженности',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'029',@link_self,'Создание условий для реализации информационной политики и внедрения современных технологий на загрязненных территориях','ВР_2011',0,'',0,'','Создание условий для реализации информационной политики и внедрения современных технологий на загрязненных территориях',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'030',@link_self,'Обеспечение выполнения международных обязательств Российской Федерации в области преодоления последствий радиационных катастроф и инцидентов','ВР_2011',0,'',0,'','Обеспечение выполнения международных обязательств Российской Федерации в области преодоления последствий радиационных катастроф и инцидентов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'032',@link_self,'Совершенствование системы мониторинга и прогнозирования чрезвычайных ситуаций, в том числе обусловленных сейсмической опасностью и цунами','ВР_2011',0,'',0,'','Совершенствование системы мониторинга и прогнозирования чрезвычайных ситуаций, в том числе обусловленных сейсмической опасностью и цунами',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'039',@link_self,'Финансирование расходов, осуществляемое за счет средств, поступающих от сдачи в аренду имущества, закрепленного за государственными организациями','ВР_2011',0,'',0,'','Финансирование расходов, осуществляемое за счет средств, поступающих от сдачи в аренду имущества, закрепленного за государственными организациями',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'040',@link_self,'Специальные мероприятия','ВР_2011',0,'',0,'','Специальные мероприятия',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'043',@link_self,'Ликвидация и вывод из эксплуатации ядерно и радиационно опасных объектов, наземных стратегических ракетных комплексов и объектов хранения, производства и уничтожения оружия','ВР_2011',0,'',0,'','Ликвидация и вывод из эксплуатации ядерно и радиационно опасных объектов, наземных стратегических ракетных комплексов и объектов хранения, производства и уничтожения оружия',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'044',@link_self,'Уничтожение запасов химического оружия','ВР_2011',0,'',0,'','Уничтожение запасов химического оружия',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'046',@link_self,'Мероприятия, связанные с реализацией задач по утилизации и ликвидации вооружения, военной техники, иного производственно-технического оборудования и имущества, уничтожению запасов химического оружия','ВР_2011',0,'',0,'','Мероприятия, связанные с реализацией задач по утилизации и ликвидации вооружения, военной техники, иного производственно-технического оборудования и имущества, уничтожению запасов химического оружия',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'047',@link_self,'Инспекционная деятельность','ВР_2011',0,'',0,'','Инспекционная деятельность',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'048',@link_self,'Осуществление прав пользования и распоряжения лесами, их охрана, защита и воспроизводство','ВР_2011',0,'',0,'','Осуществление прав пользования и распоряжения лесами, их охрана, защита и воспроизводство',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'049',@link_self,'Мероприятия в области оборонно-промышленного комплекса','ВР_2011',0,'',0,'','Мероприятия в области оборонно-промышленного комплекса',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'050',@link_self,'Уточнение фактических и прогнозируемых границ зон радиоактивного загрязнения и подготовка карт радиоактивного загрязнения отдельных территорий','ВР_2011',0,'',0,'','Уточнение фактических и прогнозируемых границ зон радиоактивного загрязнения и подготовка карт радиоактивного загрязнения отдельных территорий',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'051',@link_self,'Мероприятия по обеспечению взрывопожаробезопасного состояния систем хранения и эксплуатации специальных объектов','ВР_2011',0,'',0,'','Мероприятия по обеспечению взрывопожаробезопасного состояния систем хранения и эксплуатации специальных объектов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'053',@link_self,'Мероприятия, связанные с реализацией задач по утилизации, включая расходы по реабилитации береговых территорий, транспортировке и переработке отработавшего ядерного топлива','ВР_2011',0,'',0,'','Мероприятия, связанные с реализацией задач по утилизации, включая расходы по реабилитации береговых территорий, транспортировке и переработке отработавшего ядерного топлива',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'054',@link_self,'Мероприятия по землеустройству и землепользованию','ВР_2011',0,'',0,'','Мероприятия по землеустройству и землепользованию',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'055',@link_self,'Закупки специальной космической техники, организация запусков и управление полетами космических аппаратов','ВР_2011',0,'',0,'','Закупки специальной космической техники, организация запусков и управление полетами космических аппаратов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'056',@link_self,'Государственная поддержка космической деятельности в интересах федеральных нужд','ВР_2011',0,'',0,'','Государственная поддержка космической деятельности в интересах федеральных нужд',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'063',@link_self,'Утилизация и ликвидация вооружения и военной техники','ВР_2011',0,'',0,'','Утилизация и ликвидация вооружения и военной техники',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'064',@link_self,'Информатика','ВР_2011',0,'',0,'','Информатика',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'067',@link_self,'Мероприятия в области здравоохранения','ВР_2011',0,'',0,'','Мероприятия в области здравоохранения',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'070',@link_self,'Мероприятия по обеспечению взрывопожаробезопасного состояния систем хранения и эксплуатации специальных объектов (особых базисных складов) хранения взрывчатых материалов','ВР_2011',0,'',0,'','Мероприятия по обеспечению взрывопожаробезопасного состояния систем хранения и эксплуатации специальных объектов (особых базисных складов) хранения взрывчатых материалов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'073',@link_self,'Отдельные мероприятия по другим видам транспорта','ВР_2011',0,'',0,'','Отдельные мероприятия по другим видам транспорта',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'074',@link_self,'Государственная поддержка организаций при выполнении комплекса мероприятий по хранению отработавшего ядерного топлива и радиоактивных отходов, блоков реакторных отсеков и судов атомного технологического обслуживания','ВР_2011',0,'',0,'','Государственная поддержка организаций при выполнении комплекса мероприятий по хранению отработавшего ядерного топлива и радиоактивных отходов, блоков реакторных отсеков и судов атомного технологического обслуживания',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'075',@link_self,'Закупки специальной космической техники для обеспечения функционирования системы ГЛОНАСС','ВР_2011',0,'',0,'','Закупки специальной космической техники для обеспечения функционирования системы ГЛОНАСС',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'076',@link_self,'Мероприятия в области национальной обороны','ВР_2011',0,'',0,'','Мероприятия в области национальной обороны',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'077',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Объединенная авиастроительная корпорация"','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Объединенная авиастроительная корпорация"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'080',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Федеральная сетевая компания Единой энергетической системы"
','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Федеральная сетевая компания Единой энергетической системы"
',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'082',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "РусГидро"','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "РусГидро"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'083',@link_self,'Взнос в уставный капитал открытого акционерного общества "Росагролизинг"','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Росагролизинг"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'084',@link_self,'Взнос в уставный капитал открытого акционерного общества "Российский сельскохозяйственный банк";
','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Российский сельскохозяйственный банк";
',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'087',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Объединенная судостроительная корпорация"','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Объединенная судостроительная корпорация"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'088',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "РОСНАНО"','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "РОСНАНО"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'089',@link_self,'Взнос в уставный капитал открытого акционерного общества "Особые экономические зоны"','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Особые экономические зоны"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'090',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "РАО Энергетические системы Востока"','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "РАО Энергетические системы Востока"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'092',@link_self,'Утилизация атомных подводных лодок, судов атомного технологического обслуживания, надводных кораблей с ядерными энергетическими установками, плавучих емкостей для хранения жидких радиоактивных отходов','ВР_2011',0,'',0,'','Утилизация атомных подводных лодок, судов атомного технологического обслуживания, надводных кораблей с ядерными энергетическими установками, плавучих емкостей для хранения жидких радиоактивных отходов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'093',@link_self,'Государственная поддержка организаций при выполнении комплекса мероприятий в области утилизации и ликвидации накопленных компонентов ядерных боеприпасов','ВР_2011',0,'',0,'','Государственная поддержка организаций при выполнении комплекса мероприятий в области утилизации и ликвидации накопленных компонентов ядерных боеприпасов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'094',@link_self,'Мероприятия, связанные с созданием и обеспечением функционирования системы геофизического мониторинга','ВР_2011',0,'',0,'','Мероприятия, связанные с созданием и обеспечением функционирования системы геофизического мониторинга',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'095',@link_self,'Мероприятия по повышению безопасности остановленных и функционирующих ядерно и радиационно опасных объектов, включая мероприятия при обращении с накопленными отработавшим ядерным топливом и радиоактивными отходами','ВР_2011',0,'',0,'','Мероприятия по повышению безопасности остановленных и функционирующих ядерно и радиационно опасных объектов, включая мероприятия при обращении с накопленными отработавшим ядерным топливом и радиоактивными отходами',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'096',@link_self,'Мероприятия по созданию систем геодезического и навигационно-картографического обеспечения','ВР_2011',0,'',0,'','Мероприятия по созданию систем геодезического и навигационно-картографического обеспечения',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'098',@link_self,'Развитие инфраструктуры города Мирного','ВР_2011',0,'',0,'','Развитие инфраструктуры города Мирного',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'099',@link_self,'Субсидии на осуществление мероприятий по обеспечению жильем граждан Российской Федерации, проживающих в сельской местности','ВР_2011',0,'',0,'','Субсидии на осуществление мероприятий по обеспечению жильем граждан Российской Федерации, проживающих в сельской местности',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'100',@link_self,'Расходы на выплаты персоналу в целях обеспечения выполнения функций государственными органами, казенными учреждениями, органами управления государственными внебюджетными фондами','ВР_2011',0,'',0,'','Расходы на выплаты персоналу в целях обеспечения выполнения функций государственными органами, казенными учреждениями, органами управления государственными внебюджетными фондами',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Расходы на выплаты персоналу в целях обеспечения выполнения функций государственными органами, казенными учреждениями, органами управления государственными внебюджетными фондами', 'Расходы на выплаты персоналу в целях обеспечения выполнения функций государственными органами, казенными учреждениями, органами управления государственными внебюджетными фондами', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'104',@link_self,'Государственное образовательное учреждение высшего профессионального образования "Северо-Кавказский государственный технический университет", общежитие, г. Ставрополь','ВР_2011',0,'',0,'','Государственное образовательное учреждение высшего профессионального образования "Северо-Кавказский государственный технический университет", общежитие, г. Ставрополь',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'105',@link_self,'Федеральное государственное образовательное учреждение "Всероссийский детский центр "Орленок", жилой дом, пос. Новомихайловский, Туапсинский район, Краснодарский край','ВР_2011',0,'',0,'','Федеральное государственное образовательное учреждение "Всероссийский детский центр "Орленок", жилой дом, пос. Новомихайловский, Туапсинский район, Краснодарский край',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'106',@link_self,'Государственное образовательное учреждение высшего профессионального образования "Дагестанский государственный педагогический университет", общежитие, г. Махачкала, Республика Дагестан','ВР_2011',0,'',0,'','Государственное образовательное учреждение высшего профессионального образования "Дагестанский государственный педагогический университет", общежитие, г. Махачкала, Республика Дагестан',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'108',@link_self,'Федеральное государственное образовательное учреждение высшего профессионального образования "Национальный исследовательский технологический университет "МИСиС", общежитие, г. Москва','ВР_2011',0,'',0,'','Федеральное государственное образовательное учреждение высшего профессионального образования "Национальный исследовательский технологический университет "МИСиС", общежитие, г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'109',@link_self,'Государственное образовательное учреждение высшего профессионального образования для инвалидов с нарушением опорно-двигательной системы "Московский государственный социально-гуманитарный институт", общежитие, г. Москва','ВР_2011',0,'',0,'','Государственное образовательное учреждение высшего профессионального образования для инвалидов с нарушением опорно-двигательной системы "Московский государственный социально-гуманитарный институт", общежитие, г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '100' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'110',@link_self,'Расходы на выплаты персоналу казенных учреждений','ВР_2011',0,'',0,'','Расходы на выплаты персоналу казенных учреждений','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '110' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'111',@link_self,'Фонд оплаты труда казенных учреждений и взносы по обязательному социальному страхованию','ВР_2011',0,'',0,'','Фонд оплаты труда казенных учреждений и взносы по обязательному социальному страхованию','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Фонд оплаты труда и страховые взносы', 'Фонд оплаты труда и страховые взносы', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Фонд оплаты труда казенных учреждений и взносы по обязательному социальному страхованию', 'Фонд оплаты труда казенных учреждений и взносы по обязательному социальному страхованию', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '110' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'112',@link_self,'Иные выплаты персоналу казенных учреждений, за исключением фонда оплаты труда','ВР_2011',0,'',0,'','Иные выплаты персоналу казенных учреждений, за исключением фонда оплаты труда','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты персоналу казенных учреждений, за исключением фонда оплаты труда', 'Иные выплаты персоналу казенных учреждений, за исключением фонда оплаты труда', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты персоналу, за исключением фонда оплаты труда', 'Иные выплаты персоналу, за исключением фонда оплаты труда', '20000101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '110' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'113',@link_self,'Иные выплаты, за исключением фонда оплаты труда казенных учреждений, лицам, привлекаемым согласно законодательству для выполнения отдельных полномочий','ВР_2011',0,'',0,'','Иные выплаты, за исключением фонда оплаты труда казенных учреждений, лицам, привлекаемым согласно законодательству для выполнения отдельных полномочий','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты, за исключением фонда оплаты труда казенных учреждений, лицам, привлекаемым согласно законодательству для выполнения отдельных полномочий', 'Иные выплаты, за исключением фонда оплаты труда казенных учреждений, лицам, привлекаемым согласно законодательству для выполнения отдельных полномочий', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Федеральное государственное автономное образовательное учреждение высшего профессионального образования "Дальневосточный федеральный университет", общежитие, г. Владивосток, Приморский край', 'Федеральное государственное автономное образовательное учреждение высшего профессионального образования "Дальневосточный федеральный университет", общежитие, г. Владивосток, Приморский край', '20000101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'116',@link_self,'Государственное образовательное учреждение высшего профессионального образования "Тверской государственный университет", г. Тверь, 9-этажные общежития № 4 и № 5 с блоком обслуживания по ул. Плеханова, г. Тверь','ВР_2011',0,'',0,'','Государственное образовательное учреждение высшего профессионального образования "Тверской государственный университет", г. Тверь, 9-этажные общежития № 4 и № 5 с блоком обслуживания по ул. Плеханова, г. Тверь',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'117',@link_self,'Государственное образовательное учреждение высшего профессионального образования "Нижегородский государственный технический университет им. Р.Е. Алексеева", комплекс общежитий с блоком обслуживания по Казанскому шоссе в Нижегородском районе г. Нижний','ВР_2011',0,'',0,'','Государственное образовательное учреждение высшего профессионального образования "Нижегородский государственный технический университет им. Р.Е. Алексеева", комплекс общежитий с блоком обслуживания по Казанскому шоссе в Нижегородском районе г. Нижний Новгород (2-я очередь строительства)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '100' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'120',@link_self,'Расходы на выплаты персоналу государственных (муниципальных) органов','ВР_2011',0,'',0,'','Расходы на выплаты персоналу государственных (муниципальных) органов','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Расходы на выплаты персоналу государственных (муниципальных) органов', 'Расходы на выплаты персоналу государственных (муниципальных) органов', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Расходы на выплаты персоналу государственных органов', 'Расходы на выплаты персоналу государственных органов', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '120' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'121',@link_self,'Фонд оплаты труда государственных (муниципальных) органов и взносы по обязательному социальному страхованию','ВР_2011',0,'',0,'','Фонд оплаты труда государственных (муниципальных) органов и взносы по обязательному социальному страхованию','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Фонд оплаты труда государственных (муниципальных) органов и взносы по обязательному социальному страхованию', 'Фонд оплаты труда государственных (муниципальных) органов и взносы по обязательному социальному страхованию', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Фонд оплаты труда и страховые взносы', 'Фонд оплаты труда и страховые взносы', '20000101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '120' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'122',@link_self,'Иные выплаты персоналу государственных (муниципальных) органов, за исключением фонда оплаты труда','ВР_2011',0,'',0,'','Иные выплаты персоналу государственных (муниципальных) органов, за исключением фонда оплаты труда','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты персоналу государственных (муниципальных) органов, за исключением фонда оплаты труда', 'Иные выплаты персоналу государственных (муниципальных) органов, за исключением фонда оплаты труда', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты персоналу, за исключением фонда оплаты труда', 'Иные выплаты персоналу, за исключением фонда оплаты труда', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '100' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'130',@link_self,'Расходы на выплаты персоналу в сфере национальной безопасности, правоохранительной деятельности и обороны','ВР_2011',0,'',0,'','Расходы на выплаты персоналу в сфере национальной безопасности, правоохранительной деятельности и обороны','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '130' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'131',@link_self,'Денежное довольствие военнослужащих и сотрудников, имеющих специальные звания','ВР_2011',0,'',0,'','Денежное довольствие военнослужащих и сотрудников, имеющих специальные звания','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Денежное довольствие военнослужащих и приравненных к ним лиц', 'Денежное довольствие военнослужащих и приравненных к ним лиц', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Денежное довольствие военнослужащих и сотрудников, имеющих специальные звания', 'Денежное довольствие военнослужащих и сотрудников, имеющих специальные звания', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '130' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'133',@link_self,'Расходы на выплаты военнослужащим и сотрудникам, имеющим специальные звания, зависящие от размера денежного довольствия','ВР_2011',0,'',0,'','Расходы на выплаты военнослужащим и сотрудникам, имеющим специальные звания, зависящие от размера денежного довольствия','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Расходы на выплаты военнослужащим и сотрудникам, имеющим специальные звания, зависящие от размера денежного довольствия', 'Расходы на выплаты военнослужащим и сотрудникам, имеющим специальные звания, зависящие от размера денежного довольствия', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Расходы на выплаты, зависящие от размера денежного довольствия', 'Расходы на выплаты, зависящие от размера денежного довольствия', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '130' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'134',@link_self,'Иные выплаты персоналу и сотрудникам, имеющим специальные звания','ВР_2011',0,'',0,'','Иные выплаты персоналу и сотрудникам, имеющим специальные звания','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты персоналу и сотрудникам, имеющим специальные звания', 'Иные выплаты персоналу и сотрудникам, имеющим специальные звания', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты персоналу, за исключением денежного довольствия', 'Иные выплаты персоналу, за исключением денежного довольствия', '20000101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'137',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Стрела", г. Тула
Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Стрела", г. Тула
','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Стрела", г. Тула','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'139',@link_self,'Взнос в уставный капитал открытого акционерного общества "Туламашзавод", г. Тула','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Туламашзавод", г. Тула','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '100' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'140',@link_self,'Расходы на выплаты персоналу государственных внебюджетных фондов','ВР_2011',0,'',0,'','Расходы на выплаты персоналу государственных внебюджетных фондов','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '140' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'141',@link_self,'Фонд оплаты труда и страховые взносы','ВР_2011',0,'',0,'','Фонд оплаты труда и страховые взносы','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '140' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'142',@link_self,'Иные выплаты персоналу, за исключением фонда оплаты труда','ВР_2011',0,'',0,'','Иные выплаты персоналу, за исключением фонда оплаты труда','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'164',@link_self,'Взнос в уставный капитал открытого акционерного общества "НИИ молекулярной электроники и завод "Микрон", г. Москва, Зеленоград','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "НИИ молекулярной электроники и завод "Микрон", г. Москва, Зеленоград',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'167',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт "Электрон", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт "Электрон", г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'169',@link_self,'Взнос в уставный капитал открытого акционерного общества "Военно-промышленная корпорация "Научно-производственное объединение машиностроения", г. Реутов, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Военно-промышленная корпорация "Научно-производственное объединение машиностроения", г. Реутов, Московская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'170',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Созвездие", г. Воронеж','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Созвездие", г. Воронеж',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'171',@link_self,'Взнос в уставный капитал открытого акционерного общества "Усть-Среднеканская ГЭС", г. Магадан, Магаданская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Усть-Среднеканская ГЭС", г. Магадан, Магаданская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'173',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственный центр "Полюс", г. Томск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственный центр "Полюс", г. Томск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'174',@link_self,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Стрела", г. Оренбург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Стрела", г. Оренбург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'175',@link_self,'Взнос в уставный капитал открытого акционерного общества "Конструкторское бюро химавтоматики", г. Воронеж','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Конструкторское бюро химавтоматики", г. Воронеж',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'178',@link_self,'Взнос в уставный капитал открытого акционерного общества "Корпорация "Тактическое ракетное вооружение", г. Королев, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Корпорация "Тактическое ракетное вооружение", г. Королев, Московская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'180',@link_self,'Взнос в уставный капитал открытого акционерного общества "Объединенная авиастроительная корпорация", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Объединенная авиастроительная корпорация", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'181',@link_self,'Взнос в уставный капитал открытого акционерного общества Научно-производственное объединение "Сатурн", г. Рыбинск, Ярославская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества Научно-производственное объединение "Сатурн", г. Рыбинск, Ярославская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'184',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Авионика", г. Раменское, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Авионика", г. Раменское, Московская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'186',@link_self,'Взнос в уставный капитал открытого акционерного общества "Авиационная холдинговая компания "Сухой", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Авиационная холдинговая компания "Сухой", г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'188',@link_self,'Взнос в уставный капитал открытого акционерного общества "Красногорский завод имени С.А. Зверева", г. Красногорск, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Красногорский завод имени С.А. Зверева", г. Красногорск, Московская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'189',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Научно-производственное объединение "Электромашина", г. Челябинск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Научно-производственное объединение "Электромашина", г. Челябинск','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'198',@link_self,'Взнос в уставный капитал Ордена Почета открытого акционерного общества "Телемеханика", г. Нальчик, Кабардино-Балкарская Республика','ВР_2011',0,'',0,'','Взнос в уставный капитал Ордена Почета открытого акционерного общества "Телемеханика", г. Нальчик, Кабардино-Балкарская Республика','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'200',@link_self,'Закупка товаров, работ и услуг для государственных (муниципальных) нужд','ВР_2011',0,'',0,'','Закупка товаров, работ и услуг для государственных (муниципальных) нужд','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ и услуг  для государственных нужд', 'Закупка товаров, работ и услуг  для государственных нужд', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ и услуг для государственных (муниципальных) нужд', 'Закупка товаров, работ и услуг для государственных (муниципальных) нужд', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ и услуг для государственных нужд', 'Закупка товаров, работ и услуг для государственных нужд', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'201',@link_self,'Взнос в уставный капитал открытого акционерного общества "Тамбовский завод "Революционный труд", г. Тамбов','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Тамбовский завод "Революционный труд", г. Тамбов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'202',@link_self,'Взнос в уставный капитал открытого акционерного общества "Тамбовский научно-исследовательский институт радиотехники "ЭФИР", г. Тамбов','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Тамбовский научно-исследовательский институт радиотехники "ЭФИР", г. Тамбов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'203',@link_self,'Взнос в уставный капитал открытого акционерного общества "Тамбовский завод "Октябрь", г. Тамбов','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Тамбовский завод "Октябрь", г. Тамбов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'205',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Алмаз", г. Ростов-на-Дону','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Алмаз", г. Ростов-на-Дону','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'208',@link_self,'Взнос в уставный капитал открытого акционерного общества "Завод "Навигатор", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Завод "Навигатор", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '200' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'210',@link_self,'Разработка, закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Разработка, закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Разработка, закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа', 'Разработка, закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Разработка, закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества', 'Разработка, закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества', '20000101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'211',@link_self,'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','ВР_2011',0,'',0,'','Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения', 'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'212',@link_self,'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения','ВР_2011',0,'',0,'','Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения', 'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'213',@link_self,'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества вне рамок государственного оборонного заказа','ВР_2011',0,'',0,'','Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества вне рамок государственного оборонного заказа',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества вне рамок государственного оборонного заказа', 'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества вне рамок государственного оборонного заказа', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'214',@link_self,'Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','ВР_2011',0,'',0,'','Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения', 'Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'215',@link_self,'Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения','ВР_2011',0,'',0,'','Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения', 'Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'216',@link_self,'Фундаментальные исследования в интересах национальной обороны, национальной безопасности и правоохранительной деятельности в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','ВР_2011',0,'',0,'','Фундаментальные исследования в интересах национальной обороны, национальной безопасности и правоохранительной деятельности в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'217',@link_self,'Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','ВР_2011',0,'',0,'','Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исследования в области разработки вооружений, военной и  специальной техники, продукции производственно-технического  назначения и имущества в рамках государственного оборонного  заказа в целях обеспечения государственной программы вооружения', 'Исследования в области разработки вооружений, военной и  специальной техники, продукции производственно-технического  назначения и имущества в рамках государственного оборонного  заказа в целях обеспечения государственной программы вооружения', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения', 'Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'218',@link_self,'Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа вне рамок государственной программы вооружения','ВР_2011',0,'',0,'','Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа вне рамок государственной программы вооружения','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исследования в области разработки вооружений, военной и  специальной техники, продукции производственно-технического  назначения и имущества в рамках государственного оборонного  заказа вне рамок государственной программы вооружения', 'Исследования в области разработки вооружений, военной и  специальной техники, продукции производственно-технического  назначения и имущества в рамках государственного оборонного  заказа вне рамок государственной программы вооружения', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа вне рамок государственной программы вооружения', 'Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа вне рамок государственной программы вооружения', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'219',@link_self,'Закупка работ и услуг в целях обеспечения мероприятий в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Закупка работ и услуг в целях обеспечения мероприятий в рамках государственного оборонного заказа',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка работ и услуг в целях обеспечения мероприятий в рамках государственного оборонного заказа', 'Закупка работ и услуг в целях обеспечения мероприятий в рамках государственного оборонного заказа', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '200' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'220',@link_self,'Закупка товаров, работ и услуг для обеспечения специальным топливом и горюче-смазочными материалами, продовольственного и вещевого обеспечения органов в сфере национальной безопасности, правоохранительной деятельности и обороны','ВР_2011',0,'',0,'','Закупка товаров, работ и услуг для обеспечения специальным топливом и горюче-смазочными материалами, продовольственного и вещевого обеспечения органов в сфере национальной безопасности, правоохранительной деятельности и обороны',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ и услуг для обеспечения специальным  топливом и горюче-смазочными материалами, продовольственного и вещевого обеспечения органов в сфере национальной безопасности, правоохранительной деятельности и обороны', 'Закупка товаров, работ и услуг для обеспечения специальным  топливом и горюче-смазочными материалами, продовольственного и вещевого обеспечения органов в сфере национальной безопасности, правоохранительной деятельности и обороны', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ и услуг для обеспечения специальным топливом и горюче-смазочными материалами, продовольственного и вещевого обеспечения органов в сфере национальной безопасности, правоохранительной деятельности и обороны', 'Закупка товаров, работ и услуг для обеспечения специальным топливом и горюче-смазочными материалами, продовольственного и вещевого обеспечения органов в сфере национальной безопасности, правоохранительной деятельности и обороны', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '220' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'221',@link_self,'Обеспечение специальным топливом и горюче-смазочными материалами в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Обеспечение специальным топливом и горюче-смазочными материалами в рамках государственного оборонного заказа','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '220' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'222',@link_self,'Обеспечение специальным топливом и горюче-смазочными материалами вне рамок государственного оборонного заказа','ВР_2011',0,'',0,'','Обеспечение специальным топливом и горюче-смазочными материалами вне рамок государственного оборонного заказа','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '220' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'223',@link_self,'Продовольственное обеспечение в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Продовольственное обеспечение в рамках государственного оборонного заказа',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Продовольственное обеспечение в рамках  государственного оборонного заказа', 'Продовольственное обеспечение в рамках  государственного оборонного заказа', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Продовольственное обеспечение в рамках государственного оборонного заказа', 'Продовольственное обеспечение в рамках государственного оборонного заказа', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '220' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'224',@link_self,'Продовольственное обеспечение вне рамок государственного оборонного заказа','ВР_2011',0,'',0,'','Продовольственное обеспечение вне рамок государственного оборонного заказа',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Продовольственное обеспечение вне рамок государственного оборонного заказа', 'Продовольственное обеспечение вне рамок государственного оборонного заказа', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '220' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'225',@link_self,'Вещевое обеспечение в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Вещевое обеспечение в рамках государственного оборонного заказа','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Вещевое обеспечение в рамках государственного оборонного заказа', 'Вещевое обеспечение в рамках государственного оборонного заказа', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '220' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'226',@link_self,'Вещевое обеспечение вне рамок государственного оборонного заказа','ВР_2011',0,'',0,'','Вещевое обеспечение вне рамок государственного оборонного заказа','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '200' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'230',@link_self,'Закупка товаров, работ, услуг в целях формирования государственного материального резерва','ВР_2011',0,'',0,'','Закупка товаров, работ, услуг в целях формирования государственного материального резерва','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'232',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Старт", г. Великий Новгород','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Старт", г. Великий Новгород','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'234',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский технологический институт "Техномаш", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский технологический институт "Техномаш", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'235',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Гранит-Электрон", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Гранит-Электрон", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'237',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт "Курс", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт "Курс", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'238',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Моринформсистема-Агат", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Моринформсистема-Агат", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'239',@link_self,'Взнос в уставный капитал открытого акционерного общества "Таганрогский завод "Прибой", г. Таганрог, Ростовская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Таганрогский завод "Прибой", г. Таганрог, Ростовская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '200' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'240',@link_self,'Иные закупки товаров, работ и услуг для обеспечения государственных (муниципальных) нужд','ВР_2011',0,'',0,'','Иные закупки товаров, работ и услуг для обеспечения государственных (муниципальных) нужд','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные закупки товаров, работ и услуг для государственных нужд', 'Иные закупки товаров, работ и услуг для государственных нужд', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Иные закупки товаров, работ и услуг для обеспечения государственных (муниципальных) нужд', 'Иные закупки товаров, работ и услуг для обеспечения государственных (муниципальных) нужд', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '240' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'241',@link_self,'Научно-исследовательские и опытно-конструкторские работы','ВР_2011',0,'',0,'','Научно-исследовательские и опытно-конструкторские работы','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '240' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'242',@link_self,'Закупка товаров, работ, услуг в сфере информационно-коммуникационных технологий','ВР_2011',0,'',0,'','Закупка товаров, работ, услуг в сфере информационно-коммуникационных технологий','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '240' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'243',@link_self,'Закупка товаров, работ, услуг в целях капитального ремонта государственного (муниципального) имущества','ВР_2011',0,'',0,'','Закупка товаров, работ, услуг в целях капитального ремонта государственного (муниципального) имущества','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ, услуг в целях капитального ремонта государственного (муниципального) имущества', 'Закупка товаров, работ, услуг в целях капитального ремонта государственного (муниципального) имущества', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ, услуг в целях капитального ремонта государственного имущества', 'Закупка товаров, работ, услуг в целях капитального ремонта государственного имущества', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '240' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'244',@link_self,'Прочая закупка товаров, работ и услуг для обеспечения государственных (муниципальных) нужд','ВР_2011',0,'',0,'','Прочая закупка товаров, работ и услуг для обеспечения государственных (муниципальных) нужд','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Прочая закупка товаров, работ и услуг для государственных нужд', 'Прочая закупка товаров, работ и услуг для государственных нужд', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Прочая закупка товаров, работ и услуг для обеспечения государственных (муниципальных) нужд', 'Прочая закупка товаров, работ и услуг для обеспечения государственных (муниципальных) нужд', '20140206'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'246',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-технологическая компания "Ригель", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-технологическая компания "Ригель", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'254',@link_self,'Взнос в уставный капитал открытого акционерного общества "Объединенная промышленная корпорация "Оборонпром", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Объединенная промышленная корпорация "Оборонпром", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'256',@link_self,'Взнос в уставный капитал открытого акционерного общества "Светлана", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Светлана", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'257',@link_self,'Взнос в уставный капитал открытого акционерного общества "Авангард", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Авангард", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'262',@link_self,'Взнос в уставный капитал открытого акционерного общества "Российская электроника", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Российская электроника", г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'269',@link_self,'Поддержание объектов наземной инфраструктуры системы ГЛОНАСС, информационно-техническое обеспечение мероприятий по реализации федеральной целевой программы','ВР_2011',0,'',0,'','Поддержание объектов наземной инфраструктуры системы ГЛОНАСС, информационно-техническое обеспечение мероприятий по реализации федеральной целевой программы',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'270',@link_self,'Органы управления государственных внебюджетных фондов','ВР_2011',0,'',0,'','Органы управления государственных внебюджетных фондов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'278',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Квант", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Квант", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'291',@link_self,'Взнос в уставный капитал открытого акционерного общества "Пермский завод "Машиностроитель", г. Пермь','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Пермский завод "Машиностроитель", г. Пермь','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'296',@link_self,'Взнос в уставный капитал открытого акционерного общества "Институт пластмасс имени Г.С. Петрова", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Институт пластмасс имени Г.С. Петрова", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'300',@link_self,'Социальное обеспечение и иные выплаты населению','ВР_2011',0,'',0,'','Социальное обеспечение и иные выплаты населению',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Социальное обеспечение и иные выплаты населению', 'Социальное обеспечение и иные выплаты населению', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'302',@link_self,'Мероприятия, связанные с развитием инфраструктуры космодрома "Плесецк" космодромов на 2006 - 2015 годы".','ВР_2011',0,'',0,'','Мероприятия, связанные с развитием инфраструктуры космодрома "Плесецк" космодромов на 2006 - 2015 годы".',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'304',@link_self,'Взнос в уставный капитал открытого акционерного общества "Камчатский газоэнергетический комплекс" (г. Петропавловск-Камчатский, Камчатский край)','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Камчатский газоэнергетический комплекс" (г. Петропавловск-Камчатский, Камчатский край)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'305',@link_self,'Взнос в уставный капитал Советско-Монгольского акционерного общества "Улан-Баторская железная дорога"
','ВР_2011',0,'',0,'','Взнос в уставный капитал Советско-Монгольского акционерного общества "Улан-Баторская железная дорога"
',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'309',@link_self,'Взнос в уставный капитал открытого акционерного общества "Федеральная сетевая компания Единой энергетической системы" (г. Москва)','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Федеральная сетевая компания Единой энергетической системы" (г. Москва)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '300' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'310',@link_self,'Публичные нормативные социальные  выплаты гражданам','ВР_2011',0,'',0,'','Публичные нормативные социальные  выплаты гражданам','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '310' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'311',@link_self,'Пенсии, выплачиваемые по пенсионному страхованию населения','ВР_2011',0,'',0,'','Пенсии, выплачиваемые по пенсионному страхованию населения','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '310' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'312',@link_self,'Иные пенсии, социальные доплаты к пенсиям','ВР_2011',0,'',0,'','Иные пенсии, социальные доплаты к пенсиям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные пенсии, социальные доплаты к пенсиям', 'Иные пенсии, социальные доплаты к пенсиям', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Пенсии, выплачиваемые организациями сектора государственного управления', 'Пенсии, выплачиваемые организациями сектора государственного управления', '20000101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '310' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'313',@link_self,'Пособия, компенсации, меры социальной поддержки по публичным нормативным обязательствам','ВР_2011',0,'',0,'','Пособия, компенсации, меры социальной поддержки по публичным нормативным обязательствам','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Пособия и компенсации по публичным нормативным обязательствам', 'Пособия и компенсации по публичным нормативным обязательствам', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Пособия, компенсации, меры социальной поддержки по публичным нормативным обязательствам', 'Пособия, компенсации, меры социальной поддержки по публичным нормативным обязательствам', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '310' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'314',@link_self,'Меры социальной поддержки населения по публичным нормативным обязательствам','ВР_2011',0,'',0,'','Меры социальной поддержки населения по публичным нормативным обязательствам','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '310' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'317',@link_self,'Федеральный научно-клинический центр детской гематологии, онкологии и иммунологии, г. Москва','ВР_2011',0,'',0,'','Федеральный научно-клинический центр детской гематологии, онкологии и иммунологии, г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '300' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'320',@link_self,'Социальные выплаты гражданам, кроме публичных нормативных социальных выплат','ВР_2011',0,'',0,'','Социальные выплаты гражданам, кроме публичных нормативных социальных выплат','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '320' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'321',@link_self,'Пособия, компенсации и иные социальные выплаты гражданам, кроме публичных нормативных обязательств','ВР_2011',0,'',0,'','Пособия, компенсации и иные социальные выплаты гражданам, кроме публичных нормативных обязательств','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Пособия и компенсации гражданам и иные социальные выплаты, кроме публичных нормативных обязательств', 'Пособия и компенсации гражданам и иные социальные выплаты, кроме публичных нормативных обязательств', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Пособия, компенсации и иные социальные выплаты гражданам, кроме публичных нормативных обязательств', 'Пособия, компенсации и иные социальные выплаты гражданам, кроме публичных нормативных обязательств', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '320' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'322',@link_self,'Субсидии гражданам на приобретение жилья','ВР_2011',0,'',0,'','Субсидии гражданам на приобретение жилья','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '320' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'323',@link_self,'Приобретение товаров, работ, услуг в пользу граждан в целях их социального обеспечения','ВР_2011',0,'',0,'','Приобретение товаров, работ, услуг в пользу граждан в целях их социального обеспечения','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Приобретение товаров, работ, услуг в пользу граждан в целях их социального обеспечения', 'Приобретение товаров, работ, услуг в пользу граждан в целях их социального обеспечения', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Приобретение товаров, работ, услуг в пользу граждан', 'Приобретение товаров, работ, услуг в пользу граждан', '20000101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'326',@link_self,'Стр-во в СПб Орловского тоннеля под р.Невой','ВР_2011',0,'',0,'','Строительство в г. Санкт-Петербурге Орловского тоннеля под р. Невой в рамках развития Волго-Балтийского водного пути',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'327',@link_self,'Стр-во нового выхода на МКАД с М-1 "Беларусь"','ВР_2011',0,'',0,'','Строительство нового выхода на Московскую кольцевую автомобильную дорогу с федеральной автомобильной дороги М-1 "Беларусь" Москва - Минск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'328',@link_self,'Стр-во скор.а/д Москва-СПб на участке 15-58 км','ВР_2011',0,'',0,'','Строительство скоростной автомобильной дороги Москва - Санкт-Петербург на участке 15-й км - 58-й км',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'329',@link_self,'Комплексное развитие Нижнего Приангарья','ВР_2011',0,'',0,'','Комплексное развитие Нижнего Приангарья',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '300' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'330',@link_self,'Публичные нормативные выплаты гражданам несоциального характера','ВР_2011',0,'',0,'','Публичные нормативные выплаты гражданам несоциального характера',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Публичные нормативные выплаты гражданам несоциального характера', 'Публичные нормативные выплаты гражданам несоциального характера', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'331',@link_self,'Комплекс нефтепер.и нефтехим.заводов в Нижнекамске','ВР_2011',0,'',0,'','Комплекс нефтеперерабатывающих и нефтехимических заводов в г. Нижнекамске',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'332',@link_self,'Стр-во ж/д станции Кызыл-Курагино (осв.МСБ Р.Тыва)','ВР_2011',0,'',0,'','Строительство железнодорожной станции Кызыл-Курагино в увязке с освоением минерально-сырьевой базы Республики Тыва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'335',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственный центр "Ригель", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственный центр "Ригель", г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'336',@link_self,'Разр.пр.док.на стр-во скор.а/д Москва-СПб 58-684км','ВР_2011',0,'',0,'','Разработка проектной документации на строительство скоростной автомобильной дороги Москва - Санкт-Петербург на участке км 58 - км 684 (с последующей эксплуатацией на платной основе)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'338',@link_self,'Разр.пр.док.для инв.проекта "Компл.разв.Юж.Якутии"','ВР_2011',0,'',0,'','Разработка проектной документации для реализации инвестиционного проекта "Комплексное развитие Южной Якутии"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'339',@link_self,'Компл.прогр.стр-ва объектов водосн.Ростова-на-Дону','ВР_2011',0,'',0,'','Комплексная программа строительства и реконструкции объектов водоснабжения и водоотведения г. Ростова-на-Дону и юго-запада Ростовской области',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '300' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'340',@link_self,'Стипендии','ВР_2011',0,'',0,'','Стипендии',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Стипендии', 'Стипендии', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'343',@link_self,'Мероприятия по развитию методической составляющей системы обеспечения единства измерений в наноиндустрии и безопасности создания и применения объектов наноиндустрии','ВР_2011',0,'',0,'','Мероприятия по развитию методической составляющей системы обеспечения единства измерений в наноиндустрии и безопасности создания и применения объектов наноиндустрии',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'344',@link_self,'Взнос в уставный капитал открытого акционерного общества "Рыбинский завод приборостроения", г. Рыбинск, Ярославская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Рыбинский завод приборостроения", г. Рыбинск, Ярославская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'345',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Рубин", г. Пенза','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Рубин", г. Пенза',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'346',@link_self,'Взнос в уставный капитал открытого акционерного общества "Инженерно-маркетинговый центр Концерна "Вега", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Инженерно-маркетинговый центр Концерна "Вега", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'347',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Правдинский радиозавод", г. Балахна, Нижегородская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Правдинский радиозавод", г. Балахна, Нижегородская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'349',@link_self,'Взнос в уставный капитал открытого акционерного общества "Воронежский научно-исследовательский институт "Вега", г. Воронеж','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Воронежский научно-исследовательский институт "Вега", г. Воронеж',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '300' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'350',@link_self,'Премии и гранты','ВР_2011',0,'',0,'','Премии и гранты','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'353',@link_self,'Взнос в уставный капитал открытого акционерного общества "Институт электронных управляющих машин им. И.С. Брука", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Институт электронных управляющих машин им. И.С. Брука", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'357',@link_self,'Взнос в уставный капитал открытого акционерного общества "Информационные спутниковые системы" имени академика М.Ф. Решетнёва", г. Железногорск, Красноярский край','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Информационные спутниковые системы" имени академика М.Ф. Решетнёва", г. Железногорск, Красноярский край',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'358',@link_self,'Взнос в уставный капитал открытого акционерного общества "Сибирские приборы и системы", г. Омск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Сибирские приборы и системы", г. Омск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'359',@link_self,'Взнос в уставный капитал открытого акционерного общества "Российские железные дороги"','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Российские железные дороги"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '300' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'360',@link_self,'Иные выплаты населению','ВР_2011',0,'',0,'','Иные выплаты населению','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'361',@link_self,'Разр.пр.док.для инв.проекта "Стр-во ЦКАД Моск.об."','ВР_2011',0,'',0,'','Разработка проектной документации для реализации инвестиционного проекта "Строительство Центральной кольцевой автомобильной дороги Московской области"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'362',@link_self,'Взнос в уставный капитал Черноморского банка торговли и развития','ВР_2011',0,'',0,'','Взнос в уставный капитал Черноморского банка торговли и развития',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'363',@link_self,'Взнос в уставный капитал открытого акционерного общества "Дальневосточная энергетическая управляющая компания", г. Владивосток','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Дальневосточная энергетическая управляющая компания", г. Владивосток',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'365',@link_self,'Взнос в уставный капитал открытого акционерного общества "Пермская научно-производственная приборостроительная компания", г. Пермь','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Пермская научно-производственная приборостроительная компания", г. Пермь',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'367',@link_self,'Взнос в уставный капитал открытого акционерного общества "Равенство", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Равенство", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'368',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт полупроводниковых приборов", г. Томск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт полупроводниковых приборов", г. Томск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'369',@link_self,'Взнос в уставный капитал открытого акционерного общества "Агрегатное конструкторское бюро "Якорь", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Агрегатное конструкторское бюро "Якорь", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'370',@link_self,'Взнос в уставный капитал открытого акционерного общества "Полигон", г. Томск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Полигон", г. Томск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'372',@link_self,'Стр-во и посл.экспл. МПК "Юг-2" в порту Усть-Луга','ВР_2011',0,'',0,'','Строительство и последующая эксплуатация многопрофильного перегрузочного комплекса "Юг-2" в морском торговом порту Усть-Луга',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'373',@link_self,'Вторая очередь программы развития агропромышленного комплекса Тамбовской области','ВР_2011',0,'',0,'','Вторая очередь программы развития агропромышленного комплекса Тамбовской области','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'374',@link_self,'Создание регионального индустриального парка в городе Невинномысске Ставропольского края','ВР_2011',0,'',0,'','Создание регионального индустриального парка в городе Невинномысске Ставропольского края','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'375',@link_self,'Создание завода по производству полиэтилентерефталата (ПЭТФ) пищевого и текстильного назначения производственной мощностью 486 тыс. тонн в год','ВР_2011',0,'',0,'','Создание завода по производству полиэтилентерефталата (ПЭТФ) пищевого и текстильного назначения производственной мощностью 486 тыс. тонн в год','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'376',@link_self,'Взнос в уставный капитал открытого акционерного общества "КазХимНИИ", г. Казань','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "КазХимНИИ", г. Казань',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'377',@link_self,'Строительство и эксплуатация на платной основе мостовых переходов  через реку Кама и реку Буй у города Камбарка на автомобильной дороге  Ижевск - Сарапул - Камбарка - граница Республики Башкортостан в Удмуртской Республике','ВР_2011',0,'',0,'','Строительство и эксплуатация на платной основе мостовых переходов  через реку Кама и реку Буй у города Камбарка на автомобильной дороге  Ижевск - Сарапул - Камбарка - граница Республики Башкортостан в Удмуртской Республике','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'378',@link_self,'Взнос в уставный капитал открытого акционерного общества "Электростальское научно-производственное объединение "Неорганика", г. Электросталь, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Электростальское научно-производственное объединение "Неорганика", г. Электросталь, Московская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'379',@link_self,'Взнос в уставный капитал открытого акционерного общества "Корпорация "Росхимзащита", г. Тамбов','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Корпорация "Росхимзащита", г. Тамбов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'383',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Государственный ракетный центр имени академика В.П.Макеева", г. Миасс','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Государственный ракетный центр имени академика В.П.Макеева", г. Миасс','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'386',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Геофизика-Космос", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Геофизика-Космос", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'387',@link_self,'Поддержка программ развития инновационной инфраструктуры, включая поддержку малого инновационного предпринимательства, в федеральных образовательных учреждениях высшего профессионального образования','ВР_2011',0,'',0,'','Поддержка программ развития инновационной инфраструктуры, включая поддержку малого инновационного предпринимательства, в федеральных образовательных учреждениях высшего профессионального образования',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'388',@link_self,'Развитие сети национальных университетов и других образовательных учреждений','ВР_2011',0,'',0,'','Развитие сети национальных университетов и других образовательных учреждений',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'390',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственная корпорация "Уралвагонзавод" имени Ф.Э. Дзержинского", г. Нижний Тагил, Свердловская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственная корпорация "Уралвагонзавод" имени Ф.Э. Дзержинского", г. Нижний Тагил, Свердловская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'391',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Центральный научно-исследовательский институт "Буревестник", г. Нижний Новгород','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Центральный научно-исследовательский институт "Буревестник", г. Нижний Новгород','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'392',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Государственный научно-исследовательский институт машиностроения  имени В.В. Бахирева", г. Дзержинск, Нижегородская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Государственный научно-исследовательский институт машиностроения  имени В.В. Бахирева", г. Дзержинск, Нижегородская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'393',@link_self,'Взнос в уставный капитал открытого акционерного общества "Северный Рейд", г. Северодвинск, Архангельская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Северный Рейд", г. Северодвинск, Архангельская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'394',@link_self,'Взнос в уставный капитал открытого акционерного общества "Северное производственное объединение "АРКТИКА", г. Северодвинск, Архангельская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Северное производственное объединение "АРКТИКА", г. Северодвинск, Архангельская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'396',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт морской теплотехники", г. Ломоносов,  г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт морской теплотехники", г. Ломоносов,  г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'397',@link_self,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Северное машиностроительное предприятие", г. Северодвинск, Архангельская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Северное машиностроительное предприятие", г. Северодвинск, Архангельская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'400',@link_self,'Капитальные вложения в объекты недвижимого имущества государственной (муниципальной) собственности','ВР_2011',0,'',0,'','Капитальные вложения в объекты недвижимого имущества государственной (муниципальной) собственности','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции', 'Бюджетные инвестиции', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Капитальные вложения в объекты недвижимого имущества государственной (муниципальной) собственности', 'Капитальные вложения в объекты недвижимого имущества государственной (муниципальной) собственности', '20140206'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'401',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн ПВО "Алмаз-Антей", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн ПВО "Алмаз-Антей", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'402',@link_self,'Взнос в уставный капитал открытого акционерного общества "Сибирский химический комбинат", г. Северск, Томская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Сибирский химический комбинат", г. Северск, Томская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'403',@link_self,'Взнос в уставный капитал открытого акционерного общества "Государственный научный центр - Научно-исследовательский институт атомных реакторов", г. Димитровград-10, Ульяновская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Государственный научный центр - Научно-исследовательский институт атомных реакторов", г. Димитровград-10, Ульяновская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'404',@link_self,'Взнос в уставный капитал открытого акционерного общества "Опытное Конструкторское Бюро Машиностроения имени И.И. Африкантова, г. Нижний Новгород','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Опытное Конструкторское Бюро Машиностроения имени И.И. Африкантова, г. Нижний Новгород',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'407',@link_self,'Взнос в уставный капитал открытого акционерного общества "Ступинская металлургическая компания", г. Ступино, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Ступинская металлургическая компания", г. Ступино, Московская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'409',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт химикатов для полимерных материалов", г. Тамбов','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт химикатов для полимерных материалов", г. Тамбов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '400' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'410',@link_self,'Бюджетные инвестиции','ВР_2011',0,'',0,'','Бюджетные инвестиции','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности федеральным государственным учреждениям', 'Бюджетные инвестиции в объекты государственной собственности федеральным государственным учреждениям', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции', 'Бюджетные инвестиции', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'411',@link_self,'Бюджетные инвестиции в объекты государственной собственности казенным учреждениям вне рамок государственного оборонного заказа','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты государственной собственности казенным учреждениям вне рамок государственного оборонного заказа',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности казенным учреждениям вне рамок государственного оборонного заказа', 'Бюджетные инвестиции в объекты государственной собственности казенным учреждениям вне рамок государственного оборонного заказа', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'412',@link_self,'Бюджетные инвестиции на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность','ВР_2011',0,'',0,'','Бюджетные инвестиции на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты  государственной собственности казенным учреждениям  в рамках государственного оборонного заказа', 'Бюджетные инвестиции в объекты  государственной собственности казенным учреждениям  в рамках государственного оборонного заказа', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности казенным учреждениям в рамках государственного оборонного заказа', 'Бюджетные инвестиции в объекты государственной собственности казенным учреждениям в рамках государственного оборонного заказа', '20130101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность', 'Бюджетные инвестиции на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'413',@link_self,'Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности бюджетным учреждениям вне рамок государственного оборонного заказа', 'Бюджетные инвестиции в объекты государственной собственности бюджетным учреждениям вне рамок государственного оборонного заказа', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа', 'Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'414',@link_self,'Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности бюджетным учреждениям в рамках государственного оборонного заказа', 'Бюджетные инвестиции в объекты государственной собственности бюджетным учреждениям в рамках государственного оборонного заказа', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа', 'Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'415',@link_self,'Бюджетные инвестиции в соответствии с концессионными соглашениями','ВР_2011',0,'',0,'','Бюджетные инвестиции в соответствии с концессионными соглашениями','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности автономным учреждениям', 'Бюджетные инвестиции в объекты государственной собственности автономным учреждениям', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в соответствии с концессионными соглашениями', 'Бюджетные инвестиции в соответствии с концессионными соглашениями', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'418',@link_self,'Взнос в уставный капитал открытого акционерного общества "Атомспецтранс", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Атомспецтранс", г. Москва','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '400' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'420',@link_self,'Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '420' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'421',@link_self,'Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям, основанным на праве оперативного управления','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям, основанным на праве оперативного управления',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям, основанным на праве оперативного управления', 'Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям, основанным на праве оперативного управления', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '420' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'422',@link_self,'Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям, основанным на праве хозяйственного ведения','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям, основанным на праве хозяйственного ведения','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'424',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт технической физики и автоматизации", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт технической физики и автоматизации", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'425',@link_self,'Взнос в уставный капитал открытого акционерного общества "Высокотехнологический научно-исследовательский институт неорганических материалов имени академика А.А. Бочвара", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Высокотехнологический научно-исследовательский институт неорганических материалов имени академика А.А. Бочвара", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'427',@link_self,'Взнос в уставный капитал открытого акционерного общества "Московская специализированная типография № 27", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Московская специализированная типография № 27", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'429',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Морское подводное оружие - Гидроприбор", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Морское подводное оружие - Гидроприбор", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '400' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'430',@link_self,'Бюджетные инвестиции в объекты государственных внебюджетных фондов','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты государственных внебюджетных фондов',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственных внебюджетных фондов', 'Бюджетные инвестиции в объекты государственных внебюджетных фондов', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'431',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центр технологии судостроения и судоремонта", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центр технологии судостроения и судоремонта", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'433',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центр судоремонта "Звездочка", г. Северодвинск, Архангельская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центр судоремонта "Звездочка", г. Северодвинск, Архангельская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'434',@link_self,'Взнос в уставный капитал открытого акционерного общества "Дальневосточный завод "Звезда", г. Большой Камень, Приморский край','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Дальневосточный завод "Звезда", г. Большой Камень, Приморский край',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'435',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт двигателей", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт двигателей", г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'437',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Центральный научно-исследовательский институт "Электроприбор", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Центральный научно-исследовательский институт "Электроприбор", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'438',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Научно-производственное объединение "Аврора", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Научно-производственное объединение "Аврора", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'439',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Центральное морское конструкторское бюро "Алмаз", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Центральное морское конструкторское бюро "Алмаз", г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '400' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'440',@link_self,'Бюджетные инвестиции на приобретение объектов недвижимого имущества','ВР_2011',0,'',0,'','Бюджетные инвестиции на приобретение объектов недвижимого имущества','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции на приобретение объектов недвижимого имущества', 'Бюджетные инвестиции на приобретение объектов недвижимого имущества', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '440' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'441',@link_self,'Бюджетные инвестиции на приобретение объектов недвижимого имущества казенным учреждениям','ВР_2011',0,'',0,'','Бюджетные инвестиции на приобретение объектов недвижимого имущества казенным учреждениям','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции на приобретение объектов недвижимого имущества казенным учреждениям', 'Бюджетные инвестиции на приобретение объектов недвижимого имущества казенным учреждениям', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '440' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'442',@link_self,'Бюджетные инвестиции на приобретение объектов недвижимого имущества бюджетным учреждениям','ВР_2011',0,'',0,'','Бюджетные инвестиции на приобретение объектов недвижимого имущества бюджетным учреждениям',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции на приобретение объектов недвижимого имущества бюджетным учреждениям', 'Бюджетные инвестиции на приобретение объектов недвижимого имущества бюджетным учреждениям', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '440' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'443',@link_self,'Бюджетные инвестиции на приобретение объектов недвижимого имущества автономным учреждениям','ВР_2011',0,'',0,'','Бюджетные инвестиции на приобретение объектов недвижимого имущества автономным учреждениям','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'444',@link_self,'Реализация государственных полномочий по проведению государственной экологической экспертизы','ВР_2011',0,'',0,'','Реализация государственных полномочий по проведению государственной экологической экспертизы',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '440' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'446',@link_self,'Бюджетные инвестиции на приобретение объектов недвижимого имущества государственным внебюджетным фондам','ВР_2011',0,'',0,'','Бюджетные инвестиции на приобретение объектов недвижимого имущества государственным внебюджетным фондам','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '400' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'450',@link_self,'Бюджетные инвестиции иным юридическим лицам','ВР_2011',0,'',0,'','Бюджетные инвестиции иным юридическим лицам','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'453',@link_self,'Взнос в уставный капитал открытого акционерного общества Красноярский машиностроительный завод", г. Красноярск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества Красноярский машиностроительный завод", г. Красноярск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'454',@link_self,'Первая очередь программы развития АПК Тамб.обл.','ВР_2011',0,'',0,'','Первая очередь программы развития АПК Тамбовской области',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'457',@link_self,'Взнос в уставный капитал открытого акционерного общества "Государственный научно-исследовательский и проектный институт редкометаллической промышленности "Гиредмет", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Государственный научно-исследовательский и проектный институт редкометаллической промышленности "Гиредмет", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'458',@link_self,'Взнос в уставный капитал открытого акционерного общества "Опытный завод тугоплавких металлов и твердых сплавов", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Опытный завод тугоплавких металлов и твердых сплавов", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'459',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственная корпорация "Системы прецизионного приборостроения", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственная корпорация "Системы прецизионного приборостроения", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'460',@link_self,'Субсидии на осуществление капитальных вложений бюджетным и автономным учреждениям, государственным унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений бюджетным и автономным учреждениям, государственным унитарным предприятиям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'460',@link_self,'Субсидии на осуществление капитальных вложений бюджетным и автономным учреждениям, государственным унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений бюджетным и автономным учреждениям, государственным унитарным предприятиям',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт физических измерений", г. Пенза', 'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт физических измерений", г. Пенза', '20000101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'461',@link_self,'Взнос в уставный капитал открытого акционерного общества "Уральский научно-исследовательский институт композиционных материалов", г. Пермь','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Уральский научно-исследовательский институт композиционных материалов", г. Пермь',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'461',@link_self,'Субсидии на приобретение объектов недвижимости бюджетным учреждениям','ВР_2011',0,'',0,'','Субсидии на приобретение объектов недвижимости бюджетным учреждениям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на приобретение объектов недвижимости бюджетным учреждениям', 'Субсидии на приобретение объектов недвижимости бюджетным учреждениям', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'462',@link_self,'Взнос в уставный капитал открытого акционерного общества "Зеленодольское проектно-конструкторское бюро", г. Зеленодольск, Республика Татарстан','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Зеленодольское проектно-конструкторское бюро", г. Зеленодольск, Республика Татарстан',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'462',@link_self,'Субсидии на приобретение объектов недвижимости автономным учреждениям','ВР_2011',0,'',0,'','Субсидии на приобретение объектов недвижимости автономным учреждениям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на приобретение объектов недвижимости автономным учреждениям', 'Субсидии на приобретение объектов недвижимости автономным учреждениям', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'463',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательское проектно-технологическое бюро "Онега", г. Северодвинск, Архангельская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательское проектно-технологическое бюро "Онега", г. Северодвинск, Архангельская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'463',@link_self,'Субсидии на приобретение объектов недвижимости государственным унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на приобретение объектов недвижимости государственным унитарным предприятиям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на приобретение объектов недвижимости государственным унитарным предприятиям', 'Субсидии на приобретение объектов недвижимости государственным унитарным предприятиям', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'464',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро морской техники "Рубин", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро морской техники "Рубин", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'464',@link_self,'Субсидии на осуществление капитальных вложений в объекты капитального строительства бюджетным учреждениям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений в объекты капитального строительства бюджетным учреждениям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на осуществление капитальных вложений в объекты капитального строительства бюджетным учреждениям', 'Субсидии на осуществление капитальных вложений в объекты капитального строительства бюджетным учреждениям', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'465',@link_self,'Взнос в уставный капитал открытого акционерного общества "Ново-Вятка", г. Киров','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Ново-Вятка", г. Киров','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'465',@link_self,'Субсидии на осуществление капитальных вложений в объекты капитального строительства автономным учреждениям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений в объекты капитального строительства автономным учреждениям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на осуществление капитальных вложений в объекты капитального строительства автономным учреждениям', 'Субсидии на осуществление капитальных вложений в объекты капитального строительства автономным учреждениям', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'466',@link_self,'Взнос в уставный капитал открытого акционерного общества "Уральский завод транспортного машиностроения", г. Екатеринбург,  Свердловская область";','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Уральский завод транспортного машиностроения", г. Екатеринбург,  Свердловская область";','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'466',@link_self,'Субсидии на осуществление капитальных вложений в объекты капитального строительства государственным унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений в объекты капитального строительства государственным унитарным предприятиям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на осуществление капитальных вложений в объекты капитального строительства государственным унитарным предприятиям', 'Субсидии на осуществление капитальных вложений в объекты капитального строительства государственным унитарным предприятиям', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'471',@link_self,'Стр-во комб-та по глуб.перераб.древ."Зел.фабрика"','ВР_2011',0,'',0,'','Строительство комбината по глубокой переработке древесины "Зеленая фабрика"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'473',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Холдинг межрегиональных распределительных сетевых компаний"','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Холдинг межрегиональных распределительных сетевых компаний"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'474',@link_self,'Металлургический завод СтавСталь. 1-ая очередь. Комплекс прокатного цеха','ВР_2011',0,'',0,'','Металлургический завод СтавСталь. 1-ая очередь. Комплекс прокатного цеха','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'475',@link_self,'Развитие инфраструктуры завода по розливу минеральной воды в  с. Средние Ачалуки Малгобекского района Республики Ингушетия','ВР_2011',0,'',0,'','Развитие инфраструктуры завода по розливу минеральной воды в  с. Средние Ачалуки Малгобекского района Республики Ингушетия','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'476',@link_self,'Строительство завода по производству гипса и гипсосодержащих строительных материалов в промышленной зоне с. Кафыр-Кумух  Республики Дагестан','ВР_2011',0,'',0,'','Строительство завода по производству гипса и гипсосодержащих строительных материалов в промышленной зоне с. Кафыр-Кумух  Республики Дагестан','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'477',@link_self,'Строительство инфраструктуры кластера по добыче стекольного сырья для производства стеклянной тары в Республике Ингушетия','ВР_2011',0,'',0,'','Строительство инфраструктуры кластера по добыче стекольного сырья для производства стеклянной тары в Республике Ингушетия','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'478',@link_self,'Создание комплекса по переработке газа Северного Каспия  в этилен, полиэтилен и полипропилен (I очередь)','ВР_2011',0,'',0,'','Создание комплекса по переработке газа Северного Каспия  в этилен, полиэтилен и полипропилен (I очередь)','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'479',@link_self,'Завод по производству  готовых лекарственных форм антибиотиков','ВР_2011',0,'',0,'','Завод по производству  готовых лекарственных форм антибиотиков','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'480',@link_self,'Стр-во объектов инфр-ры г.Уфы Р.Башкортостан','ВР_2011',0,'',0,'','Строительство объектов социальной и инженерной инфраструктуры города Уфы Республики Башкортостан',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'481',@link_self,'Чистый Дон','ВР_2011',0,'',0,'','Чистый Дон',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'482',@link_self,'Стр-во инж.сетей терр.компл.застр.р-на ул.Б.Хмельн.','ВР_2011',0,'',0,'','Строительство инженерных сетей и сооружений территории комплексной застройки района улицы Богдана Хмельницкого (Чувашская Республика)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'483',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро "Монолит", г. Городец, Нижегородская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро "Монолит", г. Городец, Нижегородская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'484',@link_self,'Взнос в уставный капитал открытого акционерного общества "Российская корпорация ракетно-космического приборостроения и информационных систем", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Российская корпорация ракетно-космического приборостроения и информационных систем", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'485',@link_self,'Массовая малоэтажная застройка в с.Воскресенское','ВР_2011',0,'',0,'','Массовая малоэтажная застройка в с. Воскресенское Ферзиковского района Калужской области',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'489',@link_self,'Взнос в уставный капитал открытого акционерного общества "Федеральная гидрогенерирующая компания", г. Красноярск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Федеральная гидрогенерирующая компания", г. Красноярск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'494',@link_self,'Взнос в уставный капитал открытого акционерного общества "Завод № 9", г. Екатеринбург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Завод № 9", г. Екатеринбург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'498',@link_self,'Разв.с-мы теплоснабжения в г.Владимир и Влад.обл.','ВР_2011',0,'',0,'','Развитие системы теплоснабжения в г. Владимир и Владимирской области',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'500',@link_self,'Межбюджетные трансферты','ВР_2011',0,'',0,'','Межбюджетные трансферты',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Межбюджетные трансферты', 'Межбюджетные трансферты', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'501',@link_self,'Стр-во и реконстр.водопр.оч.сооруж.г.Петрозаводска','ВР_2011',0,'',0,'','Строительство и реконструкция водопроводных очистных сооружений г. Петрозаводска (II этап)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'510',@link_self,'Дотации на выравнивание бюджетной обеспеченности','ВР_2011',0,'',0,'','Дотации на выравнивание бюджетной обеспеченности','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Дотации на выравнивание бюджетной обеспеченности', 'Дотации на выравнивание бюджетной обеспеченности', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Дотации', 'Дотации', '20000101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '510' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'511',@link_self,'Дотации на выравнивание бюджетной обеспеченности субъектов Российской Федерации','ВР_2011',0,'',0,'','Дотации на выравнивание бюджетной обеспеченности субъектов Российской Федерации','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '510' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'512',@link_self,'Иные дотации','ВР_2011',0,'',0,'','Иные дотации','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Дотации бюджетам субъектов Российской Федерации на поддержку мер по обеспечению сбалансированности бюджетов', 'Дотации бюджетам субъектов Российской Федерации на поддержку мер по обеспечению сбалансированности бюджетов', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Иные дотации', 'Иные дотации', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '510' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'513',@link_self,'Дотации бюджетам закрытых административно-территориальных образований, связанные со статусом закрытых административно-территориальных образований','ВР_2011',0,'',0,'','Дотации бюджетам закрытых административно-территориальных образований, связанные со статусом закрытых административно-территориальных образований','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '510' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'514',@link_self,'Дотации бюджету города Байконура','ВР_2011',0,'',0,'','Дотации бюджету города Байконура','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'517',@link_self,'Взнос в уставный капитал открытого акционерного общества "Сахалинская энергетическая компания", г. Южно-Сахалинск, Сахалинская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Сахалинская энергетическая компания", г. Южно-Сахалинск, Сахалинская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'520',@link_self,'Субсидии','ВР_2011',0,'',0,'','Субсидии','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии', 'Субсидии', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '520' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'521',@link_self,'Субсидии, за исключением субсидий на софинансирование капитальных вложений в объект государственной (муниципальной) собственности','ВР_2011',0,'',0,'','Субсидии, за исключением субсидий на софинансирование капитальных вложений в объект государственной (муниципальной) собственности','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии, за исключением субсидий на софинансирование капитальных вложений в объект государственной (муниципальной) собственности', 'Субсидии, за исключением субсидий на софинансирование капитальных вложений в объект государственной (муниципальной) собственности', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии, за исключением субсидий на софинансирование объектов капитального строительства государственной собственности и муниципальной собственности', 'Субсидии, за исключением субсидий на софинансирование объектов капитального строительства государственной собственности и муниципальной собственности', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '520' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'522',@link_self,'Субсидии на софинансирование капитальных вложений в объект государственной (муниципальной) собственности','ВР_2011',0,'',0,'','Субсидии на софинансирование капитальных вложений в объект государственной (муниципальной) собственности','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на софинансирование капитальных вложений в объект государственной (муниципальной) собственности', 'Субсидии на софинансирование капитальных вложений в объект государственной (муниципальной) собственности', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на софинансирование объектов капитального строительства государственной (муниципальной) собственности', 'Субсидии на софинансирование объектов капитального строительства государственной (муниципальной) собственности', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'523',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт точных приборов", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт точных приборов", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'524',@link_self,'Взнос в уставный капитал открытого акционерного общества "Особое конструкторское бюро Московского энергетического института", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Особое конструкторское бюро Московского энергетического института", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'525',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение измерительной техники", г. Королев, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение измерительной техники", г. Королев, Московская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'527',@link_self,'Взнос в уставный капитал открытого акционерного общества "Ордена Ленина Научно-исследовательский и конструкторский институт энерготехники имени Н.А. Доллежаля", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Ордена Ленина Научно-исследовательский и конструкторский институт энерготехники имени Н.А. Доллежаля", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'528',@link_self,'Взнос в уставный капитал открытого акционерного общества "Завод "Топаз", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Завод "Топаз", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'529',@link_self,'Взнос в уставный капитал открытого акционерного общества "Невское проектно-конструкторское бюро", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Невское проектно-конструкторское бюро", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'530',@link_self,'Субвенции','ВР_2011',0,'',0,'','Субвенции',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субвенции', 'Субвенции', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'531',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро "Лазурит", г. Нижний Новгород','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро "Лазурит", г. Нижний Новгород',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'532',@link_self,'Взнос в уставный капитал открытого акционерного общества "Ангарский электролизный химический комбинат", г. Ангарск, Иркутская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Ангарский электролизный химический комбинат", г. Ангарск, Иркутская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'533',@link_self,'Взнос в уставный капитал открытого акционерного общества "Новосибирский завод химконцентратов", г. Новосибирск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Новосибирский завод химконцентратов", г. Новосибирск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'534',@link_self,'Взнос в уставный капитал открытого акционерного общества "Приаргунское производственное горно-химическое объединение", г. Краснокаменск, Забайкальский край','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Приаргунское производственное горно-химическое объединение", г. Краснокаменск, Забайкальский край',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'535',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение электромеханики", г. Миасс, Челябинская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение электромеханики", г. Миасс, Челябинская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'536',@link_self,'Закупка специальных изделий и оборудования в целях обеспечения системы управления безопасностью полетов','ВР_2011',0,'',0,'','Закупка специальных изделий и оборудования в целях обеспечения системы управления безопасностью полетов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'537',@link_self,'Взнос Российской Федерации в уставный капитал открытого акционерного общества "Производственное объединение "Северное машиностроительное предприятие" путем размещения дополнительных акций','ВР_2011',0,'',0,'','Взнос Российской Федерации в уставный капитал открытого акционерного общества "Производственное объединение "Северное машиностроительное предприятие" путем размещения дополнительных акций',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'539',@link_self,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Уральский оптико-механический завод" имени Э.С. Яламова", г. Екатеринбург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Уральский оптико-механический завод" имени Э.С. Яламова", г. Екатеринбург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'540',@link_self,'Иные межбюджетные трансферты','ВР_2011',0,'',0,'','Иные межбюджетные трансферты',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные межбюджетные трансферты', 'Иные межбюджетные трансферты', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'550',@link_self,'Межбюджетные трансферты бюджету Фонда социального страхования Российской Федерации','ВР_2011',0,'',0,'','Межбюджетные трансферты бюджету Фонда социального страхования Российской Федерации',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Межбюджетные трансферты бюджету Фонда социального страхования Российской Федерации', 'Межбюджетные трансферты бюджету Фонда социального страхования Российской Федерации', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'553',@link_self,'Субсидии некоммерческим организациям в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта','ВР_2011',0,'',0,'','Субсидии некоммерческим организациям в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'554',@link_self,'Софинансирование объектов капитального строительства государственной собственности субъектов Российской Федерации (объектов капитального строительства собственности муниципальных образований) в рамках организации и проведения ХХII Олимпийских зимних','ВР_2011',0,'',0,'','Софинансирование объектов капитального строительства государственной собственности субъектов Российской Федерации (объектов капитального строительства собственности муниципальных образований) в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'557',@link_self,'Выполнение функций бюджетными учреждениями в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта','ВР_2011',0,'',0,'','Выполнение функций бюджетными учреждениями в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'558',@link_self,'Взнос в уставный капитал открытого акционерного общества "Холдинг межрегиональных распределительных сетевых компаний" (г. Москва) в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, ра','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Холдинг межрегиональных распределительных сетевых компаний" (г. Москва) в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'559',@link_self,'Функционирование Вооруженных сил Российской Федерации, органов в сфере национальной безопасности и правоохранительной деятельности, войск и иных воинских формирований в рамках организации и проведения XXII Олимпийских зимних игр и XI Паралимпийских з','ВР_2011',0,'',0,'','Функционирование Вооруженных сил Российской Федерации, органов в сфере национальной безопасности и правоохранительной деятельности, войск и иных воинских формирований в рамках организации и проведения XXII Олимпийских зимних игр и XI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'560',@link_self,'Межбюджетные трансферты бюджету Федерального фонда обязательного медицинского страхования','ВР_2011',0,'',0,'','Межбюджетные трансферты бюджету Федерального фонда обязательного медицинского страхования','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'570',@link_self,'Межбюджетные трансферты бюджету Пенсионного фонда Российской Федерации','ВР_2011',0,'',0,'','Межбюджетные трансферты бюджету Пенсионного фонда Российской Федерации','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'580',@link_self,'Межбюджетные трансферты бюджетам территориальных фондов обязательного медицинского страхования','ВР_2011',0,'',0,'','Межбюджетные трансферты бюджетам территориальных фондов обязательного медицинского страхования','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'585',@link_self,'Финансирование расходов, осуществляемое за счет средств, поступающих от привлечения осужденных к труду','ВР_2011',0,'',0,'','Финансирование расходов, осуществляемое за счет средств, поступающих от привлечения осужденных к труду','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'590',@link_self,'Взнос в уставный капитал открытого акционерного общества "Московский завод "Сапфир", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Московский завод "Сапфир", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'591',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственный комплекс "Технокомплекс", г. Раменское, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственный комплекс "Технокомплекс", г. Раменское, Московская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'592',@link_self,'Взнос в уставный капитал открытого акционерного общества "РЭ Комплексные системы", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "РЭ Комплексные системы", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'593',@link_self,'Взнос в уставный капитал открытого акционерного общества завод "Красное знамя", г. Рязань','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества завод "Красное знамя", г. Рязань',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'594',@link_self,'Взнос в уставный капитал открытого акционерного общества "Уральское производственное предприятие "Вектор", г. Екатеринбург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Уральское производственное предприятие "Вектор", г. Екатеринбург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'595',@link_self,'Взнос в уставный капитал открытого акционерного общества "Завод "Метеор", г. Волжский, Волгоградская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Завод "Метеор", г. Волжский, Волгоградская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'596',@link_self,'Взнос в уставный капитал открытого акционерного общества "Холдинговая компания "Новосибирский электровакуумный завод - Союз", г. Новосибирск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Холдинговая компания "Новосибирский электровакуумный завод - Союз", г. Новосибирск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'597',@link_self,'Взнос в уставный капитал открытого акционерного общества "Богородицкий завод технохимических изделий", г. Богородицк, Тульская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Богородицкий завод технохимических изделий", г. Богородицк, Тульская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'598',@link_self,'Взнос в уставный капитал открытого акционерного общества "Специальное конструкторско-технологическое бюро по релейной технике", г. Великий Новгород','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Специальное конструкторско-технологическое бюро по релейной технике", г. Великий Новгород',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'599',@link_self,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Азимут", г. Махачкала, Республика Дагестан','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Азимут", г. Махачкала, Республика Дагестан',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'600',@link_self,'Предоставление субсидий бюджетным, автономным учреждениям и иным некоммерческим организациям','ВР_2011',0,'',0,'','Предоставление субсидий бюджетным, автономным учреждениям и иным некоммерческим организациям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Предоставление субсидий бюджетным, автономным учреждениям и иным некоммерческим организациям', 'Предоставление субсидий бюджетным, автономным учреждениям и иным некоммерческим организациям', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Предоставление субсидий федеральным бюджетным, автономным учреждениям и иным некоммерческим организациям', 'Предоставление субсидий федеральным бюджетным, автономным учреждениям и иным некоммерческим организациям', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'601',@link_self,'Взнос в уставный капитал открытого акционерного общества "Российский научно-исследовательский институт "Электронстандарт", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Российский научно-исследовательский институт "Электронстандарт", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'602',@link_self,'Взнос в уставный капитал открытого акционерного общества "Холдинговая компания "Станкоинструмент", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Холдинговая компания "Станкоинструмент", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'603',@link_self,'Взнос в уставный капитал открытого акционерного общества "РАО Энергетические системы Востока", г. Благовещенск, Амурская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "РАО Энергетические системы Востока", г. Благовещенск, Амурская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'604',@link_self,'Взнос в уставный капитал открытого акционерного общества "Колымаэнерго", г. Магадан, Магаданская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Колымаэнерго", г. Магадан, Магаданская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'605',@link_self,'Взнос в уставный капитал открытого акционерного общества  "15 центральный автомобильный ремонтный завод", г. Новосибирск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "15 центральный автомобильный ремонтный завод", г. Новосибирск','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'606',@link_self,'Взнос в уставный капитал открытого акционерного общества  "172 центральный автомобильный ремонтный завод", г. Воронеж','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "172 центральный автомобильный ремонтный завод", г. Воронеж','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'607',@link_self,'Взнос в уставный капитал открытого акционерного общества  "81 бронетанковый ремонтный завод", г. Армавир, Краснодарский край','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "81 бронетанковый ремонтный завод", г. Армавир, Краснодарский край','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'608',@link_self,'Взнос в уставный капитал открытого акционерного общества  "103 бронетанковый ремонтный завод", г. пос. Атамановское, Забайкальский край','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "103 бронетанковый ремонтный завод", г. пос. Атамановское, Забайкальский край','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'609',@link_self,'Взнос в уставный капитал открытого акционерного общества  "163 бронетанковый ремонтный завод", ст-ца Кущевская, Краснодарский край','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "163 бронетанковый ремонтный завод", ст-ца Кущевская, Краснодарский край','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '600' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'610',@link_self,'Субсидии бюджетным учреждениям','ВР_2011',0,'',0,'','Субсидии бюджетным учреждениям','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии бюджетным учреждениям', 'Субсидии бюджетным учреждениям', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '610' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'611',@link_self,'Субсидии бюджетным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)','ВР_2011',0,'',0,'','Субсидии бюджетным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии бюджетным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)', 'Субсидии бюджетным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии бюджетным учреждениям на финансовое обеспечение государственного задания на оказание государственных услуг (выполнение работ)', 'Субсидии бюджетным учреждениям на финансовое обеспечение государственного задания на оказание государственных услуг (выполнение работ)', '20000101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '610' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'612',@link_self,'Субсидии бюджетным учреждениям на иные цели','ВР_2011',0,'',0,'','Субсидии бюджетным учреждениям на иные цели','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'615',@link_self,'Взнос в уставный капитал открытого акционерного общества холдинговая компания "Авиаприбор-холдинг", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества холдинговая компания "Авиаприбор-холдинг", г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'616',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Научно-производственное объединение "Альфа", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Научно-производственное объединение "Альфа", г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'617',@link_self,'Взнос в уставный капитал открытого акционерного общества "Воткинский завод", г. Воткинск, Удмуртская Республика','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Воткинский завод", г. Воткинск, Удмуртская Республика','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'618',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Вольский механический завод", г. Вольск, Саратовская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Вольский механический завод", г. Вольск, Саратовская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'619',@link_self,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Новосибирский приборостроительный завод", г. Новосибирск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Новосибирский приборостроительный завод", г. Новосибирск','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '600' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'620',@link_self,'Субсидии автономным учреждениям','ВР_2011',0,'',0,'','Субсидии автономным учреждениям','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии автономным учреждениям', 'Субсидии автономным учреждениям', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '620' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'621',@link_self,'Субсидии автономным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)','ВР_2011',0,'',0,'','Субсидии автономным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии автономным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)', 'Субсидии автономным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии автономным учреждениям на финансовое обеспечение государственного задания на оказание государственных услуг (выполнение работ)', 'Субсидии автономным учреждениям на финансовое обеспечение государственного задания на оказание государственных услуг (выполнение работ)', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '620' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'622',@link_self,'Субсидии автономным учреждениям на иные цели','ВР_2011',0,'',0,'','Субсидии автономным учреждениям на иные цели','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии автономным учреждениям на иные цели', 'Субсидии автономным учреждениям на иные цели', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'623',@link_self,'Взнос в уставный капитал открытого акционерного общества "Калужский научно-исследовательский институт телемеханических устройств", г. Калуга','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Калужский научно-исследовательский институт телемеханических устройств", г. Калуга','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'624',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт "Вектор", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт "Вектор", г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'625',@link_self,'Взнос в уставный капитал открытого акционерного общества "Информационные телекоммуникационные технологии", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Информационные телекоммуникационные технологии", г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'626',@link_self,'Взнос в уставный капитал открытого акционерного общества "Миасский машиностроительный завод", г. Миасс, Челябинская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Миасский машиностроительный завод", г. Миасс, Челябинская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'627',@link_self,'Взнос в уставный капитал открытого акционерного общества "Златоустовский машиностроительный завод", г. Златоуст, Челябинская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Златоустовский машиностроительный завод", г. Златоуст, Челябинская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'628',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Научно-исследовательский институт "Субмикрон", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Научно-исследовательский институт "Субмикрон", г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'629',@link_self,'Взнос в уставный капитал открытого акционерного общества "Протон - Пермские моторы", г. Пермь','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Протон - Пермские моторы", г. Пермь','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '600' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'630',@link_self,'Субсидии некоммерческим организациям (за исключением государственных (муниципальных) учреждений)','ВР_2011',0,'',0,'','Субсидии некоммерческим организациям (за исключением государственных (муниципальных) учреждений)','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии некоммерческим организациям  (за исключением государственных учреждений)', 'Субсидии некоммерческим организациям  (за исключением государственных учреждений)', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии некоммерческим организациям (за исключением государственных (муниципальных) учреждений)', 'Субсидии некоммерческим организациям (за исключением государственных (муниципальных) учреждений)', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии некоммерческим организациям (за исключением государственных учреждений)', 'Субсидии некоммерческим организациям (за исключением государственных учреждений)', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'631',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Спецтехника", ЗАТО "Озерный", Тверская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Спецтехника", ЗАТО "Озерный", Тверская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'632',@link_self,'Взнос в уставный капитал открытого акционерного общества  "190 Центральный ремонтный завод средств связи",  г. Рыбинск, Ярославская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "190 Центральный ремонтный завод средств связи",  г. Рыбинск, Ярославская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'633',@link_self,'Взнос в уставный капитал открытого акционерного общества "Хабаровский радиотехнический завод", г. Хабаровск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Хабаровский радиотехнический завод", г. Хабаровск','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'634',@link_self,'Взнос в уставный капитал открытого акционерного общества  "9 центральный автомобильный ремонтный завод", г. Энгельс, Саратовская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "9 центральный автомобильный ремонтный завод", г. Энгельс, Саратовская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'635',@link_self,'Взнос в уставный капитал открытого акционерного общества "Воронежский Завод Полупроводниковых Приборов - Сборка", г. Воронеж','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Воронежский Завод Полупроводниковых Приборов - Сборка", г. Воронеж','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'636',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт материалов", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт материалов", г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'637',@link_self,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Баррикады",  г. Волгоград, Волгоградская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Баррикады",  г. Волгоград, Волгоградская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'638',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Центральное конструкторское бюро "Титан", г. Волгоград, Волгоградская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Центральное конструкторское бюро "Титан", г. Волгоград, Волгоградская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'639',@link_self,'Взнос в уставный капитал открытого акционерного общества "Иркутский релейный завод", г. Иркутск, Иркутская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Иркутский релейный завод", г. Иркутск, Иркутская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'640',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Корпорация "Московский институт теплотехники" г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Корпорация "Московский институт теплотехники" г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'641',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Головное особое конструкторское бюро "Прожектор", г. Москва".','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Головное особое конструкторское бюро "Прожектор", г. Москва".','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'643',@link_self,'Взнос в уставный капитал открытого акционерного общества "Особое конструкторское бюро кабельной промышленности", г. Мытищи, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Особое конструкторское бюро кабельной промышленности", г. Мытищи, Московская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'644',@link_self,'Взнос в уставный капитал открытого акционерного общества"Научно-исследовательский и технологический институт оптического материаловедения Всероссийского научного центра "Государственныйоптический институт им. С.И. Вавилова", г. Санкт-Петербург".','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества"Научно-исследовательский и технологический институт оптического материаловедения Всероссийского научного центра "Государственныйоптический институт им. С.И. Вавилова", г. Санкт-Петербург".','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'700',@link_self,'Обслуживание государственного (муниципального) долга','ВР_2011',0,'',0,'','Обслуживание государственного (муниципального) долга','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Обслуживание государственного (муниципального) долга', 'Обслуживание государственного (муниципального) долга', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Обслуживание государственного долга Российской Федерации', 'Обслуживание государственного долга Российской Федерации', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '700' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'710',@link_self,'Обслуживание государственного долга Российской Федерации','ВР_2011',0,'',0,'','Обслуживание государственного долга Российской Федерации','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Обслуживание государственного долга Российской Федерации', 'Обслуживание государственного долга Российской Федерации', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'800',@link_self,'Иные бюджетные ассигнования','ВР_2011',0,'',0,'','Иные бюджетные ассигнования','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные бюджетные ассигнования', 'Иные бюджетные ассигнования', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'810',@link_self,'Субсидии юридическим лицам (кроме некоммерческих организаций), индивидуальным предпринимателям, физическим лицам','ВР_2011',0,'',0,'','Субсидии юридическим лицам (кроме некоммерческих организаций), индивидуальным предпринимателям, физическим лицам','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии юридическим лицам (кроме государственных учреждений)  и физическим лицам - производителям товаров, работ, услуг', 'Субсидии юридическим лицам (кроме государственных учреждений)  и физическим лицам - производителям товаров, работ, услуг', '20130101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии юридическим лицам (кроме некоммерческих организаций), индивидуальным предпринимателям, физическим лицам', 'Субсидии юридическим лицам (кроме некоммерческих организаций), индивидуальным предпринимателям, физическим лицам', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'820',@link_self,'Субсидии государственным корпорациям (компаниям)','ВР_2011',0,'',0,'','Субсидии государственным корпорациям (компаниям)','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии государственным корпорациям (компаниям)', 'Субсидии государственным корпорациям (компаниям)', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '820' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'821',@link_self,'Субсидии государственным корпорациям (компаниям) в виде имущественного взноса','ВР_2011',0,'',0,'','Субсидии государственным корпорациям (компаниям) в виде имущественного взноса','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии государственным корпорациям (компаниям) в виде имущественного взноса', 'Субсидии государственным корпорациям (компаниям) в виде имущественного взноса', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '820' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'822',@link_self,'Субсидии государственным корпорациям (компаниям) на выполнение возложенных на них государственных полномочий','ВР_2011',0,'',0,'','Субсидии государственным корпорациям (компаниям) на выполнение возложенных на них государственных полномочий','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии государственным корпорациям (компаниям) на выполнение возложенных на них государственных полномочий', 'Субсидии государственным корпорациям (компаниям) на выполнение возложенных на них государственных полномочий', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '820' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'823',@link_self,'Иные субсидии государственным корпорациям (компаниям)','ВР_2011',0,'',0,'','Иные субсидии государственным корпорациям (компаниям)','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные субсидии государственным корпорациям (компаниям)', 'Иные субсидии государственным корпорациям (компаниям)', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'830',@link_self,'Исполнение судебных актов','ВР_2011',0,'',0,'','Исполнение судебных актов','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение судебных актов', 'Исполнение судебных актов', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '830' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'831',@link_self,'Исполнение судебных актов Российской Федерации и мировых соглашений по возмещению вреда, причиненного в результате незаконных действий (бездействия) органов государственной власти (государственных органов), органов местного самоуправления либо должно','ВР_2011',0,'',0,'','Исполнение судебных актов Российской Федерации и мировых соглашений по возмещению вреда, причиненного в результате незаконных действий (бездействия) органов государственной власти (государственных органов), органов местного самоуправления либо должностных','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение судебных актов Российской Федерации и мировых соглашений по возмещению вреда, причиненного в результате  незаконных действий (бездействия) органов государственной власти (государственных органов) либо должностных лиц этих органов,  а также в з', 'Исполнение судебных актов Российской Федерации и мировых соглашений по возмещению вреда, причиненного в результате  незаконных действий (бездействия) органов государственной власти (государственных органов) либо должностных лиц этих органов,  а также в результате деятельности казенных учреждений', '20130101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение судебных актов Российской Федерации и мировых соглашений по возмещению вреда, причиненного в результате незаконных действий (бездействия) органов государственной власти (государственных органов), органов местного самоуправления либо должно', 'Исполнение судебных актов Российской Федерации и мировых соглашений по возмещению вреда, причиненного в результате незаконных действий (бездействия) органов государственной власти (государственных органов), органов местного самоуправления либо должностных', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '830' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'832',@link_self,'Исполнение судебных актов судебных органов иностранных государств, международных судов и арбитражей, определяемых международными договорами Российской Федерации, в результате незаконных действий (бездействия) органов государственной власти (государст','ВР_2011',0,'',0,'','Исполнение судебных актов судебных органов иностранных государств, международных судов и арбитражей, определяемых международными договорами Российской Федерации, в результате незаконных действий (бездействия) органов государственной власти (государственных органов) либо должностных лиц этих органов, мировых соглашений, заключенных  в рамках судебных процессов в судебных органах иностранных государств,  в международных судах и арбитражах','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение судебных актов судебных органов иностранных государств, международных судов и арбитражей, определяемых международными договорами Российской Федерации, в результате незаконных действий (бездействия) органов государственной власти (государственх', 'Исполнение судебных актов судебных органов иностранных государств, международных судов и арбитражей, определяемых международными договорами Российской Федерации, в результате незаконных действий (бездействия) органов государственной власти (государственных органов) либо должностных лиц этих органов, мировых соглашений, заключенных  в рамках судебных процессов в судебных органах иностранных государств,  в международных судах и арбитражах', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'840',@link_self,'Исполнение государственных (муниципальных) гарантий без права регрессного требования гаранта к принципалу или уступки гаранту прав требования бенефициара к принципалу','ВР_2011',0,'',0,'','Исполнение государственных (муниципальных) гарантий без права регрессного требования гаранта к принципалу или уступки гаранту прав требования бенефициара к принципалу','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение государственных (муниципальных) гарантий без права регрессного требования гаранта к принципалу или уступки гаранту прав требования бенефициара к принципалу', 'Исполнение государственных (муниципальных) гарантий без права регрессного требования гаранта к принципалу или уступки гаранту прав требования бенефициара к принципалу', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение государственных гарантий без права регрессного требования гаранта к принципалу или уступки гаранту прав требования бенефициара к принципалу', 'Исполнение государственных гарантий без права регрессного требования гаранта к принципалу или уступки гаранту прав требования бенефициара к принципалу', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '840' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'841',@link_self,'Исполнение государственных гарантий Российской Федерации','ВР_2011',0,'',0,'','Исполнение государственных гарантий Российской Федерации','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение государственных гарантий Российской Федерацией', 'Исполнение государственных гарантий Российской Федерацией', '20130101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение государственных гарантий Российской Федерации', 'Исполнение государственных гарантий Российской Федерации', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'850',@link_self,'Уплата налогов, сборов и иных платежей','ВР_2011',0,'',0,'','Уплата налогов, сборов и иных платежей','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Уплата налогов, сборов и иных платежей', 'Уплата налогов, сборов и иных платежей', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '850' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'851',@link_self,'Уплата налога на имущество организаций и земельного налога','ВР_2011',0,'',0,'','Уплата налога на имущество организаций и земельного налога','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Уплата налога на имущество организаций и земельного налога', 'Уплата налога на имущество организаций и земельного налога', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '850' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'852',@link_self,'Уплата прочих налогов, сборов и иных платежей','ВР_2011',0,'',0,'','Уплата прочих налогов, сборов и иных платежей','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Уплата прочих налогов, сборов и иных платежей', 'Уплата прочих налогов, сборов и иных платежей', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'860',@link_self,'Предоставление платежей, взносов, безвозмездных перечислений субъектам международного права','ВР_2011',0,'',0,'','Предоставление платежей, взносов, безвозмездных перечислений субъектам международного права','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Предоставление платежей, взносов, безвозмездных перечислений субъектам международного права', 'Предоставление платежей, взносов, безвозмездных перечислений субъектам международного права', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '860' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'861',@link_self,'Безвозмездные перечисления субъектам международного права','ВР_2011',0,'',0,'','Безвозмездные перечисления субъектам международного права','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Безвозмездные перечисления субъектам международного права', 'Безвозмездные перечисления субъектам международного права', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '860' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'862',@link_self,'Взносы в международные организации','ВР_2011',0,'',0,'','Взносы в международные организации','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Взносы в международные организации', 'Взносы в международные организации', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '860' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'863',@link_self,'Платежи в целях обеспечения реализации соглашений с правительствами иностранных государств и международными организациями','ВР_2011',0,'',0,'','Платежи в целях обеспечения реализации соглашений с правительствами иностранных государств и международными организациями','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Платежи в целях обеспечения реализации соглашений с правительствами иностранных государств и международными организациями', 'Платежи в целях обеспечения реализации соглашений с правительствами иностранных государств и международными организациями', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'870',@link_self,'Резервные средства','ВР_2011',0,'',0,'','Резервные средства','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Резервные средства', 'Резервные средства', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'880',@link_self,'Специальные расходы','ВР_2011',0,'',0,'','Специальные расходы','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Специальные расходы', 'Специальные расходы', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '120' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'123',@link_self,'Иные выплаты, за исключением фонда оплаты труда государственных (муниципальных) органов, лицам, привлекаемым согласно законодательству для выполнения отдельных полномочий','ВР_2011',0,'',0,'','Иные выплаты, за исключением фонда оплаты труда государственных (муниципальных) органов, лицам, привлекаемым согласно законодательству для выполнения отдельных полномочий','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '450' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'451',@link_self,'Бюджетные инвестиции иным юридическим лицам в объекты капитального строительства','ВР_2011',0,'',0,'','Бюджетные инвестиции иным юридическим лицам в объекты капитального строительства','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '450' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'452',@link_self,'Бюджетные инвестиции иным юридическим лицам, за исключением бюджетных инвестиций в объекты капитального строительства','ВР_2011',0,'',0,'','Бюджетные инвестиции иным юридическим лицам, за исключением бюджетных инвестиций в объекты капитального строительства','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '700' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'720',@link_self,'Обслуживание государственного долга Российской Федерации','ВР_2011',0,'',0,'','Обслуживание государственного долга Российской Федерации','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '700' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'730',@link_self,'Обслуживание муниципального долга','ВР_2011',0,'',0,'','Обслуживание муниципального долга','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '840' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'842',@link_self,'Исполнение государственных гарантий субъекта Российской Федерации','ВР_2011',0,'',0,'','Исполнение государственных гарантий субъекта Российской Федерации','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '840' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'843',@link_self,'Исполнение муниципальных гарантий','ВР_2011',0,'',0,'','Исполнение муниципальных гарантий','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '400' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'460',@link_self,'Субсидии на осуществление капитальных вложений бюджетным и автономным учреждениям, государственным (муниципальным) унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений бюджетным и автономным учреждениям, государственным (муниципальным) унитарным предприятиям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '460' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'461',@link_self,'Субсидии  на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность бюджетным учреждениям','ВР_2011',0,'',0,'','Субсидии  на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность бюджетным учреждениям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '460' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'462',@link_self,'Субсидии на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность автономным учреждениям','ВР_2011',0,'',0,'','Субсидии на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность автономным учреждениям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '460' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'463',@link_self,'Субсидии на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность государственным (муниципальным) унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность государственным (муниципальным) унитарным предприятиям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '460' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'464',@link_self,'Субсидии на осуществление капитальных вложений в объекты капитального строительства государственной (муниципальной) собственности бюджетным учреждениям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений в объекты капитального строительства государственной (муниципальной) собственности бюджетным учреждениям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '460' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'465',@link_self,'Субсидии на осуществление капитальных вложений в объекты капитального строительства государственной (муниципальной) собственности автономным учреждениям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений в объекты капитального строительства государственной (муниципальной) собственности автономным учреждениям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '460' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'466',@link_self,'Субсидии на осуществление капитальных вложений в объекты капитального строительства государственной (муниципальной) собственности государственным (муниципальным) унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений в объекты капитального строительства государственной (муниципальной) собственности государственным (муниципальным) унитарным предприятиям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '110' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'119',@link_self,'Взносы по обязательному социальному страхованию  на выплаты по оплате труда работников и иные выплаты работникам учреждений','ВР_2011',0,'',0,'','Взносы по обязательному социальному страхованию  на выплаты по оплате труда работников и иные выплаты работникам учреждений','20160101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '120' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'129',@link_self,'Взносы по обязательному социальному страхованию на выплаты денежного содержания и иные выплаты работникам государственных (муниципальных) органов','ВР_2011',0,'',0,'','Взносы по обязательному социальному страхованию на выплаты денежного содержания и иные выплаты работникам государственных (муниципальных) органов','20160101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '140' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'149',@link_self,'Взносы по обязательному социальному страхованию на выплаты по оплате труда работников и иные выплаты работникам государственных внебюджетных фондов','ВР_2011',0,'',0,'','Взносы по обязательному социальному страхованию на выплаты по оплате труда работников и иные выплаты работникам государственных внебюджетных фондов','20160101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'416',@link_self,'Капитальные вложения на приобретение объектов недвижимого имущества государственными (муниципальными) учреждениями','ВР_2011',0,'',0,'','Капитальные вложения на приобретение объектов недвижимого имущества государственными (муниципальными) учреждениями','20160101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'417',@link_self,'Капитальные вложения на строительство объектов недвижимого имущества государственными (муниципальными) учреждениями','ВР_2011',0,'',0,'','Капитальные вложения на строительство объектов недвижимого имущества государственными (муниципальными) учреждениями','20160101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '820' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'824',@link_self,'Субсидии государственным корпорациям (компаниям) на иные цели','ВР_2011',0,'',0,'','Субсидии государственным корпорациям (компаниям) на иные цели','20160101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '850' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'853',@link_self,'Уплата иных платежей','ВР_2011',0,'',0,'','Уплата иных платежей','20140601',NULL
delete dbo.report_kbk_hist where link_up = @link


GO

GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (фев  2 2016  4:06:27:593PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503125M (Справка по консолидируемым расчётам (годовая))
-- Дата ввода : 20160101
-- Дата окончания действия :
-- Версия : 2016-02-02 16:06:27.593
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0503125M' AND [START_DATE] = '20160101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2016-02-02 16:06:27.593',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0503125M',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0503125M'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20160101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SMETA'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Справка по консолидируемым расчётам (годовая)',@vcNEW_FORM_CODE,@dNEW_START_DATE,4,1,1,1,18186,'RA_EXPORT_FORM_125#RA_IMPORT_FORM_125M',0,0,'19000101',NULL,'191н'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'svodprint_page_one_atr()','sv_0503125m_20150101.bas','','KirRepMakerMultiSheet.xls','sv_0503125m_20150101.xlt','',NULL,'RA_EXPORT_FORM_125#RA_IMPORT_FORM_125M',0,' #  #  #
RTRIM(COL2)+''|''+RTRIM(COL3)+''|''+RTRIM(COL4)+''|''+RTRIM(COL5)+''|''+LEFT(RIGHT(''**************************'' + RTRIM(COL6),26),3)+''|''+SUBSTRING(RIGHT(''**************************'' + RTRIM(COL6),26),4,14)+''|''+SUBSTRING(RIGHT(''**************************'' + RTRIM(COL6),26),18,1)+''|''+SUBSTRING(RIGHT(''**************************'' + RTRIM(COL6),26),19,5)+''|''+SUBSTRING(RIGHT(''**************************'' + RTRIM(COL6),26),24,3)+''|''+LEFT(COL9,1)+''|''+SUBSTRING(COL9,2,5)+''|''+SUBSTRING(COL9,7,3)+''|''+RTRIM(STR(COL7))+''|''+RTRIM(STR(COL7))+''|''+RTRIM(COL10)+''|''',' # # # ''|''+C1+''|''+C2+''|''+C3+''|''+C4+ ''|''+C5+C6+C7+C8+C9+''|''+C17+''|''+C18+''|''+C10+C15+C16+''|'' + C19',NULL,'225       ','REPORTS_ATR_ACC_2011,REPORTS_ATR_PRP,REPORTS_FILTER_KBK',NULL,'RO_PRINT_125_2015','|sv_0503125m_20090131_new.xlt',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Доходы', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Контрагент. Наименование',@iLINK_TABLE,1,1,1,0,2000,1,'RT_VIEW_DEPDICT_125','COL1,COL2,COL3,COL4,COL5','NAME,INN,PPP,OKTMO,CODE_EL',NULL,NULL,NULL,'%date% >= date_begin and %date% <= date_end'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Контрагент: ИНН',@iLINK_TABLE,1,1,2,0,12,1,NULL,NULL,NULL,'999999999999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Контрагент. Глава по БК',@iLINK_TABLE,0,1,3,0,3,1,'RT_VIEW_DEPDICT_125','COL1,COL2,COL3,COL4','NAME,INN,PPP,OKTMO','999',NULL,NULL,'%date% >= date_begin and %date% <= date_end'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Контрагент. Код по ОКТМО',@iLINK_TABLE,0,1,4,0,11,1,NULL,NULL,NULL,'99999999999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Контрагент. Код элемента бюджета',@iLINK_TABLE,0,1,5,0,2,1,'RT_VIEW_ELBUDG_125','COL5','CODE','99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Адм',@iLINK_TABLE,0,1,6,0,3,1,'R_SPR_ADM_2011','COL6','CODE','999',4,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Код по БК',@iLINK_TABLE,0,1,7,0,14,1,'R_SPR_DOH_14_2011','COL7','CODE','99999999999999',4,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Сумма. По дебету',@iLINK_TABLE,1,0,8,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Сумма. По кредиту',@iLINK_TABLE,1,0,9,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Код корреспондирующего счёта бюджетного учёта',@iLINK_TABLE,1,1,10,0,9,1,'R_SPR_ACCOUNTS','COL10','CODE','999999999',NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Контрагент по консолидируемым счетам. Наименование',@iLINK_TABLE,0,1,0,0,2000,1,'RT_VIEW_DEPDICT_125','COL11,COL12,COL13,COL14','NAME,INN,PPP,OKTMO',NULL,NULL,NULL,'%date% >= date_begin and %date% <= date_end'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Контрагент по конс. расчетам - ИНН',@iLINK_TABLE,1,1,11,0,12,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Контрагент по конс.расчетам - Главы по БК',@iLINK_TABLE,1,1,12,0,3,1,'RT_VIEW_DEPDICT_125','COL11,COL12,COL13,COL14','NAME,INN,PPP,OKTMO','999',NULL,NULL,'%date% >= date_begin and %date% <= date_end'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Контрагент по конс.расчетам - Код по ОКТМО',@iLINK_TABLE,1,1,13,0,11,1,NULL,NULL,NULL,'99999999999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'Признак расчёта: денежный = 1, неденежный = 0',@iLINK_TABLE,1,1,14,0,1,1,NULL,NULL,NULL,'9',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 16,'Код строки',@iLINK_TABLE,1,1,15,0,5,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 17,'Уникальный код организации',@iLINK_TABLE,1,1,16,0,8,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Доходы', @iLINK_FORM,1, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RB_CALC_0503125G_15_NEW @LSF, 1
KEY_FOX=PADR(RTRIM(COL3),3,''0'')+PADR(RTRIM(COL4),11,'' '')+RIGHT(''00''+ALLTRIM(COL5),2)+PADR(RTRIM(COL6),3,''0'')+PADR(RTRIM(COL7),14,''0'')+PADR(RTRIM(COL10),9,''0'')+RIGHT(''00000000''+ALLTRIM(STR(recno())),8)
KEY_WEB=LEFT(RTRIM(ISNULL(COL3,''''))+''000'',3)+LEFT(RTRIM(isnull(COL4,''''))+''           '',11)+RIGHT(''00''+RTRIM(ISNULL(COL5,'''')),2)+LEFT(RTRIM(ISNULL(COL6,''''))+''000'',3)+LEFT(RTRIM(ISNULL(COL7,''''))+''00000000000000'',14)+LEFT(RTRIM(ISNULL(COL10,''''))+''000000000'',9)+RIGHT(''00000000''+RTRIM(STR((select count(*) from #REP_TABLE_1 T where T.col1 <= #rep_table_1.col1)+dbo.rn_convert_number_from_word(convert(VARCHAR(80), NEWID()))+isnull(CONVERT(INT,(SELECT MAX(SUBSTRING(Code_Row,43,8)) FROM dbo.report_dinamics WHERE link_sf = (select link_saved_form FROM #REP_HEAD))) ,0))),8)

SPLIT=COL3=SUBSTRING(RTRIM(CODE_ROW)+''000'',1,3)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''000           '',4,11)#COL5=SUBSTRING(RTRIM(CODE_ROW)+''000           00'',15,2)#COL6=SUBSTRING(RTRIM(CODE_ROW)+''000           00000'',17,3)#COL7=SUBSTRING(RTRIM(CODE_ROW)+''000           0000000000000000000'',20,14)#COL10=SUBSTRING(RTRIM(CODE_ROW)+''000           0000000000000000000000000000'',34,9)#COL17=SUBSTRING(RTRIM(CODE_ROW)+''000           000000000000000000000000000000000000'',43,8)
',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Расходы', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Контрагент. Наименование',@iLINK_TABLE,1,1,1,0,2000,1,'RT_VIEW_DEPDICT_125','COL1,COL2,COL3,COL4,COL5,COL19','NAME,INN,PPP,OKTMO,CODE_EL,UCS',NULL,NULL,NULL,'%date% >= date_begin and %date% <= date_end'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Контрагент: ИНН',@iLINK_TABLE,1,1,2,0,12,1,NULL,NULL,NULL,'999999999999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Контрагент. Глава по БК',@iLINK_TABLE,0,1,3,0,3,1,'RT_VIEW_DEPDICT_125','COL1,COL2,COL3,COL4','NAME,INN,PPP,OKTMO','999',NULL,NULL,'%date% >= date_begin and %date% <= date_end'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Контрагент. Код по ОКТМО',@iLINK_TABLE,0,1,4,0,11,1,NULL,NULL,NULL,'99999999999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Контрагент. Код элемента бюджета',@iLINK_TABLE,0,1,5,0,2,1,'RT_VIEW_ELBUDG_125','COL5','CODE','99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Адм',@iLINK_TABLE,0,1,6,0,3,1,'R_SPR_ADM_2011','COL6','CODE','999',4,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'РзПр',@iLINK_TABLE,0,1,7,0,4,1,'R_SPR_RZPR_2011','COL7','CODE','9999',4,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'ЦСР',@iLINK_TABLE,0,1,8,0,10,1,'R_SPR_CSR_2011','COL8','CODE','9999999999',4,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'ВР',@iLINK_TABLE,0,1,9,0,3,1,'R_SPR_VR_2011','COL9','CODE','999',4,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Сумма. По дебету',@iLINK_TABLE,1,0,10,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Сумма. По кредиту',@iLINK_TABLE,1,0,11,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Код корреспондирующего счёта бюджетного учёта',@iLINK_TABLE,1,1,12,0,9,1,'R_SPR_ACCOUNTS','COL12','CODE','999999999',NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Контрагент по конс.расчетам: Наименование',@iLINK_TABLE,0,1,0,0,2000,1,'RT_VIEW_DEPDICT_125','COL13,COL14,COL15,COL16','NAME,INN,PPP,OKTMO',NULL,NULL,NULL,'%date% >= date_begin and %date% <= date_end'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Контрагент по конс.расчетам: ИНН',@iLINK_TABLE,1,1,13,0,12,1,NULL,NULL,NULL,'999999999999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'Контрагент по конс.расчетам: Глава по БК',@iLINK_TABLE,1,1,14,0,3,1,'RT_VIEW_DEPDICT_125','COL13,COL14,COL15,COL16','NAME,INN,PPP,OKTMO','999',NULL,NULL,'%date% >= date_begin and %date% <= date_end'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 16,'Контрагент по конс.расчетам: Код по ОКТМО',@iLINK_TABLE,1,1,15,0,11,1,NULL,NULL,NULL,'99999999999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 17,'Признак расчёта: денежный = 1, неденежный = 0',@iLINK_TABLE,1,1,16,0,1,1,NULL,NULL,NULL,'9',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 18,'Код строки',@iLINK_TABLE,1,1,17,0,250,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 19,'Уникальный код организации',@iLINK_TABLE,1,1,18,0,8,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Расходы', @iLINK_FORM,2, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RB_CALC_0503125G_15_NEW @LSF, 2
KEY_FOX=PADR(RTRIM(COL3),3,''0'')+PADR(RTRIM(COL4),11,'' '')+RIGHT(''00''+ALLTRIM(COL5),2)+PADR(RTRIM(COL6),3,''0'')+PADR(RTRIM(COL7),4,''0'')+PADR(RTRIM(COL8),10,''0'')+PADR(RTRIM(COL9),3,''0'')+PADR(RTRIM(COL12),9,''0'')+RIGHT(''00000000''+ALLTRIM(STR(recno())),8)
KEY_WEB=LEFT(RTRIM(ISNULL(COL3,''''))+''000'',3)+LEFT(RTRIM(isnull(COL4,''''))+''           '',11)+RIGHT(''00''+RTRIM(LTRIM(ISNULL(COL5,''''))),2)+LEFT(RTRIM(ISNULL(COL6,''''))+''000'',3)+LEFT(RTRIM(ISNULL(COL7,''''))+''0000'',4)+LEFT(RTRIM(ISNULL(COL8,''''))+''0000000000'',10)+LEFT(RTRIM(ISNULL(COL9,''''))+''000'',3)+LEFT(RTRIM(ISNULL(COL12,''''))+''000000000'',9)+RIGHT(''00000000''+RTRIM(STR((select count(*) from #REP_TABLE_1 T where T.col1 <= #rep_table_1.col1)+dbo.rn_convert_number_from_word(convert(VARCHAR(80), NEWID()))+isnull(CONVERT(INT,(SELECT MAX(SUBSTRING(Code_Row,46,8)) FROM dbo.report_dinamics WHERE link_sf = (select link_saved_form FROM #REP_HEAD))) ,0))),8)
SPLIT=COL3=SUBSTRING(RTRIM(CODE_ROW)+''000'',1,3)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''000           '',4,11)#COL5=SUBSTRING(RTRIM(CODE_ROW)+''000           00'',15,2)#COL6=SUBSTRING(RTRIM(CODE_ROW)+''000           00000'',17,3)#COL7=SUBSTRING(RTRIM(CODE_ROW)+''000           000000000'',20,4)#COL8=SUBSTRING(RTRIM(CODE_ROW)+''000           0000000000000000'',24,10)#COL9=SUBSTRING(RTRIM(CODE_ROW)+''000           0000000000000000000'',34,3)#COL12=SUBSTRING(RTRIM(CODE_ROW)+''000           0000000000000000000000000000'',37,9)#COL19=SUBSTRING(RTRIM(CODE_ROW)+''000           000000000000000000000000000000000000'',46,8)
DEPENDENT_COL=COL7#COL12
DEPENDENT_RELATIONS=RO_DEP_RZPR_ACC_2011_125
DEPENDENT_CALC=RzPr#Acc
',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Источники', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Контрагент. Наименование',@iLINK_TABLE,1,1,1,0,2000,1,'RT_VIEW_DEPDICT_125','COL1,COL2,COL3,COL4,COL5,COL17','NAME,INN,PPP,OKTMO,CODE_EL,UCS',NULL,NULL,NULL,'%date% >= date_begin and %date% <= date_end'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Контрагент. ИНН',@iLINK_TABLE,1,1,2,0,12,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Контрагент. Глава по БК',@iLINK_TABLE,0,1,3,0,3,1,'RT_VIEW_DEPDICT_125','COL1,COL2,COL3,COL4','NAME,INN,PPP,OKATO','999',NULL,NULL,'%date% >= date_begin and %date% <= date_end'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Контрагент. Код по ОКТМО',@iLINK_TABLE,0,1,4,0,11,1,NULL,NULL,NULL,'99999999999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Контрагент. Код элемента бюджета',@iLINK_TABLE,0,1,5,0,2,1,'RT_VIEW_ELBUDG_125','COL5','CODE','99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Адм',@iLINK_TABLE,0,1,6,0,3,1,'R_SPR_ADM_2011','COL6','CODE','999',4,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Код по БК',@iLINK_TABLE,0,1,7,0,14,1,'R_SPR_IST_125_2011','COL7','CODE','99999999999999',4,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Сумма. По дебету',@iLINK_TABLE,1,0,8,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Сумма. По кредиту',@iLINK_TABLE,1,0,9,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Код корреспондирующего счёта бюджетного учёта',@iLINK_TABLE,1,1,10,0,9,1,'R_SPR_ACCOUNTS','COL10','CODE','999999999',NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Контрагент по конс. расчетам: Наименование',@iLINK_TABLE,0,1,0,0,2000,1,'RT_VIEW_DEPDICT_125','COL11,COL12,COL13,COL14','NAME,INN,PPP,OKTMO',NULL,NULL,NULL,'%date% >= date_begin and %date% <= date_end'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Контрагент по конс. расчетам: ИНН',@iLINK_TABLE,1,1,11,0,12,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Контрагент по конс. расчетам: Глава по БК',@iLINK_TABLE,1,1,12,0,3,1,'RT_VIEW_DEPDICT_125','COL11,COL12,COL13,COL14','NAME,INN,PPP,OKTMO',NULL,NULL,NULL,'%date% >= date_begin and %date% <= date_end'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Контрагент по конс. расчетам: Код по ОКТМО',@iLINK_TABLE,1,1,13,0,11,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'Признак расчёта: денежный = 1, неденежный = 0',@iLINK_TABLE,1,1,14,0,1,1,NULL,NULL,NULL,'9',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 16,'Код строки',@iLINK_TABLE,1,1,15,0,50,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 17,'Уникальный код организации',@iLINK_TABLE,1,1,16,0,8,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Источники', @iLINK_FORM,3, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RB_CALC_0503125G_15_NEW @LSF, 3
KEY_FOX=PADR(RTRIM(COL3),3,''0'')+PADR(RTRIM(COL4),11,'' '')+RIGHT(''00''+ALLTRIM(COL5),2)+PADR(RTRIM(COL6),3,''0'')+PADR(RTRIM(COL7),14,''0'')+PADR(RTRIM(COL10),9,''0'')+RIGHT(''00000000''+ALLTRIM(STR(recno())),8)
KEY_WEB=LEFT(RTRIM(ISNULL(COL3,''''))+''000'',3)+LEFT(RTRIM(isnull(COL4,''''))+''           '',11)+RIGHT(''00''+RTRIM(LTRIM(ISNULL(COL5,''''))),2)+LEFT(RTRIM(ISNULL(COL6,''''))+''000'',3)+LEFT(RTRIM(ISNULL(COL7,''''))+''00000000000000'',14)+LEFT(RTRIM(ISNULL(COL10,''''))+''000000000'',9)+RIGHT(''00000000''+RTRIM(STR((select count(*) from #REP_TABLE_1 T where T.col1 <= #rep_table_1.col1)+dbo.rn_convert_number_from_word(convert(VARCHAR(80), NEWID()))+isnull(CONVERT(INT,(SELECT MAX(SUBSTRING(Code_Row,43,8)) FROM dbo.report_dinamics WHERE link_sf = (select link_saved_form FROM #REP_HEAD))) ,0))),8)
SPLIT=COL3=SUBSTRING(RTRIM(CODE_ROW)+''000'',1,3)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''000           '',4,11)#COL5=SUBSTRING(RTRIM(CODE_ROW)+''000           00'',15,2)#COL6=SUBSTRING(RTRIM(CODE_ROW)+''000           00000'',17,3)#COL7=SUBSTRING(RTRIM(CODE_ROW)+''000           0000000000000000000'',20,14)#COL10=SUBSTRING(RTRIM(CODE_ROW)+''000           0000000000000000000000000000'',34,9)#COL17=SUBSTRING(RTRIM(CODE_ROW)+''000           000000000000000000000000000000000000'',43,8)
',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Итоги', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Контрагент. Наименование',@iLINK_TABLE,0,1,1,0,2000,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Контрагент. ИНН',@iLINK_TABLE,1,1,1,0,12,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Контрагент. Глава по БК',@iLINK_TABLE,1,1,2,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Контрагент. Код по ОКТМО',@iLINK_TABLE,1,1,3,0,11,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Контрагент. Код элемента бюджета',@iLINK_TABLE,1,1,4,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Номер счета',@iLINK_TABLE,1,1,5,0,26,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Сумма. По дебету',@iLINK_TABLE,1,0,11,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Сумма. По кредиту',@iLINK_TABLE,1,0,12,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Код корреспондирующего счёта бюджетного учёта',@iLINK_TABLE,1,1,6,0,9,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Контрагент по конс.расчетам: Наименование',@iLINK_TABLE,0,1,7,0,2000,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Контрагент по конс.расчетам: ИНН',@iLINK_TABLE,1,1,8,0,12,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Контрагент по конс.расчетам: Глава по БК',@iLINK_TABLE,1,1,9,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Контрагент по конс.расчетам: Код по ОКТМО',@iLINK_TABLE,1,1,10,0,11,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Код строки',@iLINK_TABLE,1,1,14,0,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Итоги', @iLINK_FORM,4, @iLINK_CODE_COL,1,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'0 =  Процедура рассчёта итогов',1,2,1,'20160113','','','','0503125M','20160101','','=',9,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'т.4гр.14Фильтр:фильтр для раскраски =  т.4гр.14Фильтр:фильтр для раскраски',1,0,1,'20160113','','','','0503125M','20160101','','=',0,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'т.4гр.11 -  т.4гр.12 =  т.1гр.8 -  т.1гр.9 +  т.2гр.10 -  т.2гр.11 +  т.3гр.8 -  т.3гр.8',0,0,1,'20160113','','','','0503125M','20160101','','=',0,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'т.2гр.10 =  0 Комментарий: Для данного раздела указаные кода ЭКР не допустимы',0,0,1,'20160113','','','','0503125M','20160101','','=',0,'','Для данного раздела указаные кода ЭКР не допустимы')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'т.2гр.11 =  0 Комментарий: Для данного раздела указаные кода ЭКР не допустимы',0,0,1,'20160113','','','','0503125M','20160101','','=',0,'','Для данного раздела указаные кода ЭКР не допустимы')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.4Фильтр:Счет 140120251 =  0 Дипазон колонок:11,12 Комментарий: Справка ф. 0503125 по счету 140110151, 140120251 подлежит заполнению только в части неденежных расчетов.',0,0,1,'20160113','','7,8','','0503125M','20160101','','=',0,'','Справка ф. 0503125 по счету 140110151, 140120251 подлежит заполнению только в части неденежных расчетов.')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.4Фильтр:Счет 140110151 =  0 Дипазон колонок:11,12 Комментарий: Справка ф. 0503125 по счету 140110151, 140120251 подлежит заполнению только в части неденежных расчетов.',0,0,1,'20160113','','7,8','','0503125M','20160101','','=',0,'','Справка ф. 0503125 по счету 140110151, 140120251 подлежит заполнению только в части неденежных расчетов.')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 7
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','0','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,2,'+',NULL,NULL,NULL,NULL,0,0,'RT_CALC_0503125M_ITOG_2015(0)','Процедура рассчёта итогов','','0','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','right(CODE,1) not like ''[0123456789]''','фильтр для раскраски','','','','14','','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','right(CODE,1) not like ''[0123456789]''','фильтр для раскраски','','','','14','','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE=''ИТОГО''','','','','','7','','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE=''ИТОГО''','','','','','8','','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','1=1','','','','','8','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,4,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','1=1','','','','','9','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,5,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','1=1','','','','','10','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,6,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','1=1','','','','','11','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,7,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','1=1','','','','','8','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,8,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','1=1','','','','','8','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','substring(code,20,2)=''13'' and  substring(code,40,3)  not in (''231'',''290'')','','CODE','','','10','','2',NULL,NULL,'',0,NULL,1,'@@#"РЗПР= "+SUBSTRING(CODE,20,4)+" ЭКР="+SUBSTRING(CODE,40,3)',0)
INSERT #B VALUES(4,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','substring(code,20,2)=''13'' and  substring(code,40,3)  not in (''231'',''290'')','','CODE','','','11','','2',NULL,NULL,'',0,NULL,1,'@@#"РЗПР= "+SUBSTRING(CODE,20,4)+" ЭКР="+SUBSTRING(CODE,40,3)',0)
INSERT #B VALUES(5,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','итог_денежные_рассчёты','CODE=''итог_денежные_рассчёты''  and SUBSTRING(#REPORTS_ATR_ACC_2011#,1,9)=''140120251''','Счет 140120251','','','','','','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','итог_денежные_рассчёты','CODE=''итог_денежные_рассчёты''  and SUBSTRING(#REPORTS_ATR_ACC_2011#,1,9)=''140110151''','Счет 140110151','','','','','','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 20
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '5         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'5','Годовые формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '999999    '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'999999','формы отчетности',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2016-02-02 16:06:27.593',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 = '2016-02-02 16:06:27.593'
	BEGIN
		SELECT @vcMessage = 'Форма 0503125M с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503125M с версией от ' + @vcMessage + ' не может быть обновлена версией от 2016-02-02 16:06:27.593. Обновление отклонено.'
	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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

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

*******************************************************************************/
CREATE PROCEDURE dbo.[I_REPORT_CREATE_PROC]
	@iLINK_TABLE INT,
	@cTmpName Varchar(50)='', --требуется для подсчета подитогов 428 формы
	@iType  int  =0 --для архивных таблиц. 0 - хранимка вызова. 1 - обычная хранимка выборки, 2 - выборка из _ARH,3 - для временных таблиц
AS
   SET NOCOUNT ON
	declare @varKSRunStr	varchar(8000),
        @varKSRunStr05 varchar(8000),
		@varKSRunStr1	varchar(8000),
		@varKScStr2	varchar(8000),
		@varKScStr3	varchar(8000),
		@varKScStr3_1	varchar(8000),
        @varKSRunStrF	varchar(8000),
        @varKSRunStr05F varchar(8000),
		@varKSRunStr1F	varchar(8000),
		@varKScStr2F	varchar(8000),
		@varKScStr3F_1	varchar(8000),
		@varKScStr3F	varchar(8000),
		@varKSViewName	varchar(50),
		@varKSLink_Col	int,
		@varKSOrders		tinyint,
		@varKSiColType	tinyint,
		@varKSiLen		int,
		@varKSiIsEdit	tinyint,
		@varKSname		varchar(70),
		@varKSiVal_Type	tinyint,
		@varKSLink_Code_Col	int,
		@col_ord_for_sort int,@order_rule varchar(4000),@count_rule int,@i int,@order_rule_new varchar(8000),@order_rule_curr varchar(8000)

	DECLARE SEL_CURSOR  CURSOR STATIC LOCAL
	FOR SELECT DISTINCT LINK_Col, ORDERS, Name, Col_Type, Val_Len, IsEdited
	FROM report_coloumns WHERE LINK_Table=@iLINK_TABLE
	order by orders
	declare @cSuffix_proc varchar(200),@csuffix_table varchar(200)

set @cSuffix_table=''
set @cSuffix_PROC=''
IF @iType=1
	begin
		set @cSuffix_table=''
		set @cSuffix_proc='_OPER'
	end
IF @iType=2
	begin
		set @cSuffix_table='_ARH'
		set @cSuffix_proc='_ARH'
	end
IF @iType=3
	begin
		set @cSuffix_table=''
		set @cSuffix_proc=''
	end



SET @varKSRunStr1 = ''
set @varKSRunStr05=''
SET @varKScStr2 = ''	
SET @varKScStr3 = '' 
SET @varKScStr3_1 = '' 
SET @varKSRunStr1F = ''
set @varKSRunStr05F=''
SET @varKScStr2F = ''	
SET @varKScStr3F = '' 

declare @is_dinamic int 
IF exists (select link_Table from report_tables where link_Table = @iLINK_TABLE)
BEGIN
	select @is_dinamic=isnull(is_dinamic,0),@varKSiVal_Type = val_type, @varKSLink_Code_Col = Link_Code_Col,@order_rule=rtrim(isnull(order_rule,'')) from report_tables where link_table = @iLINK_TABLE
	set @order_rule_new=''
	--превратим @order_rule в условие
	IF @order_rule<>''
		begin
			set @order_rule_new=' case '
			set @count_rule=dbo.rn_getwordcount(@order_rule,char(13))
			set @i=1
			while @i<=@count_rule
				begin
					set @count_rule=dbo.rn_getwordcount(@order_rule,char(13))
					set @order_rule_curr=rtrim(dbo.rn_getwordnum(@order_rule,@i,char(13)))
					IF  @order_rule_curr<>''
						set @order_rule_new=@order_rule_new +' when '+ replace(UPPER(dbo.rn_getwordnum(@order_rule_curr,2,'#')),'CODE','RR.CODE_ROW')+' then '+dbo.rn_getwordnum(@order_rule_curr,1,'#')
					set @i=@i+1
				end
			set @order_rule_new=@order_rule_new+' else 0 end ' 
		end
--print @order_rule_new
	set @varKSViewName = 'dbo.RI_PROC_T'+ltrim(rtrim(@cTmpName))+ ltrim(rtrim(@iLINK_TABLE))+@cSuffix_proc
	set @varKSRunStr = ' PROCEDURE ' + @varKSViewName + '
@varKSLSF	int,
@varKSpTYPE	int=1,
@varKSPNom	int=1,
@varKSpDATE	datetime=''01/01/2003'',
@varKScCodeRow	varchar(100)='''',
@iLINK_SAVED_FORM INT = NULL,
@bDeleteEmptyRows BIT = NULL,
@tmp_table varchar(100) = '''',
@del_fcol int=0,
@all_str int =0
AS
--  Генератор I_REPORT_CREATE_PROC
--'+LTRIM(convert(char, getdate()))+'
declare @varKScode_Col	int
declare @cexec varchar(5000)
declare	@varKSLTable	int,
			@varKSLForm	int,
			@varKSLRow	int,
			@varKScCode	char(7)

select @varKScode_Col = Link_Code_Col from Report_Tables where link_table = '+ convert(varchar,@iLINK_TABLE) +'
IF @del_fcol=0 
 begin

IF @varKSLSF > 0 BEGIN
SELECT checked=0,UPD=0,del=0,link_saved_form=@varKSLSF,'
IF @varKSiVal_Type = 0 
	set @varKSRunStr = @varKSRunStr + ' rr.link_row, rr.orders, rr.Calc_orders, rr.Print_Null,
isnull((select convert(char(100),formula) from report_formula RF where RF.link_row = RR.link_row and link_col = @varKScode_Col ),'''') as code'
ELSE 
	set @varKSRunStr = @varKSRunStr + ' 0 as link_row, '+case when @order_rule<>'' then @order_rule_new else '0' end+' as orders, 0 as Calc_orders, 0 as Print_Null,
RR.Code_Row as code'

create table #Exec (ExecStr varchar(8000), orders int)
insert #Exec (ExecStr, orders)
values(@varKSRunStr, 1)

SET @varKScStr2 = ''
OPEN SEL_CURSOR
FETCH NEXT FROM SEL_CURSOR INTO @varKSLink_Col, @varKSOrders, @varKSname, @varKSiColType, @varKSiLen, @varKSiIsEdit

WHILE @@FETCH_STATUS = 0
BEGIN
	IF @varKSiLen<=0 and @varKSiColType=1
		set @varKSiLen=254
	set @varKScStr3 = ''
	IF @varKSiVal_Type = 0
	BEGIN /* Стандартные таблицы */
		IF @varKSiColType = 0
		BEGIN
			set @varKSRunStr = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) + '= coalesce((select convert(numeric(20,' + convert(char(2),@varKSiLen) + '),summa) from '+ltrim(rtrim(@cTmpName))+'report_summa'+@cSuffix_table+'  where link_saved_form = SF.link_saved_form and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' and Link_Row = RR.link_Row),0),
fcol' + ltrim(convert(varchar(7),@varKSOrders)) + '= (select left(RTRIM(formula),2500) from report_formula where link_Col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and Link_Row = RR.link_Row)'
		END
		ELSE
		BEGIN
			IF @varKSiIsEdit = 0
				set @varKSRunStr =',
isnull((select left(formula,'+ltrim(str(case when @varKSiColType=0 or @varKSiLen<250 then 254 else @varKSiLen end))+') from report_Formula RF where link_col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and RF.link_row = RR.link_row ),'''') as col' + ltrim(convert(varchar(7),@varKSOrders))
			ELSE
				set @varKSRunStr = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) + '= isnull((select convert(varchar(' + convert(char(4),@varKSiLen) + '),str_val) from report_string'+@cSuffix_table+'  where link_saved_form = SF.link_saved_form and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' and Link_Row = RR.link_Row),''''),
fcol' + ltrim(convert(varchar(7),@varKSOrders)) + '= (select left(RTRIM(formula),'+ltrim(str(@varKSiLen))+') from report_formula where link_Col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and Link_Row = RR.link_Row)'
		END
		IF @varKSiIsEdit = 0
			set @varKScStr2 =  ',
isnull((select left(formula,'+ltrim(str(case when @varKSiColType=0 or @varKSiLen<250 then 254 else @varKSiLen end))+') from report_formula RF where link_col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and RF.link_row = RR.link_row ),'''') as col' + ltrim(convert(varchar(7),@varKSOrders))
		ELSE 
		BEGIN
			IF @varKSiColType = 0
				set @varKScStr2 = ',
convert (numeric(20,' + convert(char(2),@varKSiLen) + '),0) as col'+ ltrim(convert(varchar(7),@varKSOrders))
			ELSE
				set @varKScStr2 =',
isnull(convert (VarChar(' + convert(char(4),@varKSiLen) + '),''''),'''') as col'+ ltrim(convert(varchar(7),@varKSOrders))
   			SET @varKScStr2 = @varKScStr2+',
fcol' + ltrim(convert(varchar(7),@varKSOrders)) + '= (select left(RTRIM(formula),2500) from report_formula where link_Col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and Link_Row = RR.link_Row)'
		END

		IF @varKSiColType = 0
			set @varKScStr3 = ',
isnull(convert(numeric(20,' + convert(char(2),@varKSiLen) + '),coalesce((select summa  from report_summa_all  where link_row=@varKSLRow and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col)) +' and link_saved_Form = RSF.link_saved_Form),0)),0) as col' + ltrim(rtrim(convert(varchar(5),@varKSOrders)))
	END
	ELSE /* Для динамических таблиц */
	BEGIN
		IF @varKSiColType = 0
		BEGIN
			SET @varKSRunStr = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) 
	+ '= convert(numeric(20,' + convert(char(2),@varKSiLen) 
	+ '),SUM(case when link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' then float_val else 0 end)),
fcol' + ltrim(convert(varchar(7),@varKSOrders)) + '= CAST('''' AS VARCHAR) '
			SET @varKScStr2 = ',
convert (numeric(20,' + convert(char(2),@varKSiLen) + '),0) as col'+ ltrim(convert(varchar(7),@varKSOrders))
	/* Переписать для расшифровки динамически сведеных таблиц */
			SET @varKScStr3 = ',
convert(numeric(20,' + convert(char(2),@varKSiLen) + '),coalesce((select float_val  from '+ltrim(rtrim(@cTmpName))+'REPORT_DINAMICS_ALL  where code_row=@varKScCodeRow and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col)) +' and Link_SF = RSF.link_saved_Form),0)) as col' + ltrim(rtrim(convert(varchar(5),@varKSOrders)))
		END
		ELSE
		BEGIN
			IF @varKSiLen = 0
				SET @varKSiLen = 254
			IF @varKSLink_Code_Col = @varKSLink_Col
			BEGIN /* ключевой столбец */
				SET @varKSRunStr = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) + '= RR.Code_Row '
				SET @varKScStr2 = ',
convert (VarChar(' + convert(char(4),@varKSiLen) + '),'''') as col'+ ltrim(convert(varchar(7),@varKSOrders))
			END
			ELSE
			BEGIN /* обычный текстовый столбец */
				SET @varKSRunStr = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) 
	+ '= isnull(convert(varchar(' + convert(char(4),@varKSiLen) 
	+ '),MAX(case when link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' then str_val else '''' end)),''''),
fcol' + ltrim(convert(varchar(7),@varKSOrders)) + '= CAST('''' AS VARCHAR) '
				SET @varKScStr2 = ',
isnull(convert (VarChar(' + convert(char(4),@varKSiLen) + '),''''),'''') as col'+ ltrim(convert(varchar(7),@varKSOrders))
			END
		END

		SET @varKScStr2 = @varKScStr2 + ',
fcol' + ltrim(convert(varchar(7),@varKSOrders)) + '= CAST('''' AS VARCHAR) '
	END

	insert #Exec (ExecStr, orders)
	values(@varKSRunStr, 10 + @varKSOrders)		

	insert #Exec (ExecStr, orders)
	values(@varKScStr2, 200 + @varKSOrders)		

	insert #Exec (ExecStr, orders)
	values(@varKScStr3, 400 + @varKSOrders)		
	FETCH NEXT FROM SEL_CURSOR INTO @varKSLink_Col, @varKSOrders, @varKSname, @varKSiColType, @varKSiLen, @varKSiIsEdit
END

CLOSE SEL_CURSOR

IF @varKSiVal_Type = 0 
BEGIN
	set @col_ord_for_sort = 0
	select @col_ord_for_sort = isnull(orders,0) from dbo.report_coloumns where link_table = @iLINK_TABLE and ([property] & 8) > 0
	SET @varKSRunStr05 =',
itog = 0
INTO #tabTable
FROM report_rows RR, report_saved_forms SF
WHERE RR.link_table =' + convert(varchar,@iLINK_TABLE) + '
AND SF.link_saved_form = @varKSLSF'+case when @is_dinamic=1 then 
' and (exists(select link_row from report_string'+@cSuffix_table+' RS where RS.link_saved_form=@varKSLSF and RS.link_row=RR.link_row)
or exists(select link_row from '+ltrim(rtrim(@cTmpName))+'report_summa'+@cSuffix_table+' RS where RS.link_saved_form=@varKSLSF and RS.link_row=RR.link_row))'
else '' end+
'
ORDER by orders
IF @bDeleteEmptyRows = 1 EXEC dbo.[RA_DELETE_EMPTY_ROWS] ' + CAST(@varKSiVal_Type AS VARCHAR)+ '


IF @tmp_table<>''''
 begin
    set @cExec=''SELECT * INTO ''+@tmp_table+'' FROM #tabTable order by orders ''
    execute(@cExec)
 end
 else   
    SELECT * FROM #tabTable order by '+ case @col_ord_for_sort when 0 then 'orders' else 'col'+cast(@col_ord_for_sort as varchar) end+' 
 
    DROP TABLE #tabTable

END
ELSE 
    IF @varKSLSF = 0 
	SELECT  0 as checked,  0 as UPD, 0 as del, @varKSLSF as link_saved_form, rr.link_row, rr.orders, rr.Calc_orders, rr.Print_Null,
(select convert(char(100),formula) from report_formula RF where RF.link_row = RR.link_row and link_col = @varKScode_Col ) as code'
	
SET @varKScStr2 = ',
itog = 0
	FROM report_rows RR 
	WHERE RR.link_table =' + convert(varchar,@iLINK_TABLE)+case when @is_dinamic=1 then ' and 1 = case when @all_str=0 then 0 else 1 end' else '' end+'
	ORDER by orders'
END
ELSE 
BEGIN
	set @col_ord_for_sort = 0
	select @col_ord_for_sort = isnull(orders,0) from dbo.report_coloumns where link_table = @iLINK_TABLE and ([property] & 8) > 0
	SET @varKSRunStr05 = '
   INTO #tabTable
	FROM (select RD.* from (select distinct Code_Row, Link_SF from '+ltrim(rtrim(@cTmpName))+'report_dinamics'+@cSuffix_table+' RD  inner join report_coloumns RC on RD.Link_SF = @varKSLSF and RD.Link_Col = RC.Link_Col and RC.Link_Table = ' + convert(varchar,@iLINK_TABLE) + ') RR
		left join '+ltrim(rtrim(@cTmpName))+'report_dinamics'+@cSuffix_table+' RD  on RD.Link_SF = RR.Link_SF and RR.Code_Row = RD.Code_Row 
        where RD.Link_SF=@varKSLSF) RR
	group by RR.Code_Row
	order by RR.Code_Row

  IF @bDeleteEmptyRows = 1
   BEGIN
      EXEC dbo.[RA_DELETE_EMPTY_ROWS] ' + CAST(@varKSiVal_Type AS VARCHAR)+ '
   END

    IF @tmp_table<>''''
     begin
        set @cExec=''SELECT * INTO ''+@tmp_table+'' FROM #tabTable order by orders ''
        execute(@cExec)
     end
     else   
        SELECT * FROM #tabTable order by '+ case @col_ord_for_sort when 0 then 'orders' else 'col'+cast(@col_ord_for_sort as varchar) end+' 

   DROP TABLE #tabTable
END
ELSE
    IF @varKSLSF = 0 
	SELECT  0 as checked,  0 as UPD, 0 as del, @varKSLSF as link_saved_form, 0 as link_row, 0 as orders, 0 as Calc_orders, 0 as Print_Null,

convert(varchar(100),'''') as code'

	SET @varKScStr2 = '
	FROM I_REPORT_DINAMIC_ROWS RR
	WHERE RR.link_SF = @varKSLSF
		and RR.link_table = ' + convert(varchar,@iLINK_TABLE) + '
'
END

insert #Exec (ExecStr, orders)
values(@varKSRunStr05, 100 )		

insert #Exec (ExecStr, orders)
values(@varKScStr2, 300 )		

IF @varKSiVal_Type = 0 
	set @varKScStr3 = '
	ELSE 
	BEGIN

		set @varKSLRow = - @varKSLSF
		select @varKSLTable = link_table from report_rows where link_row = @varKSLRow
	
		select @varKSLForm = link_Form from report_tables where link_table = @varKSLTable
		select @varKScCode = code from report_forms where link_form = @varKSLForm
		select 0 ord,left((select case when left(name,1) like ''[0-9]'' then '''' else  rtrim(code)+'' '' end +rtrim([name]) from dbo.DICTIONARY_DEPARTMENT where link=link_organization)+'' - ''+isnull((select [name] from dbo.KL_BUDG_TYPE A where A.link=link_type_svod),''''),254) as Org' 
ELSE  /* расшифровка для динамических таблиц */
	set @varKScStr3 = '
	ELSE 
	BEGIN
	select @varKScCode = code from report_forms where link_form = (select max(link_Form) from report_tables where link_table = ' +ltrim(rtrim(convert(varchar(10), @iLINK_TABLE))) + ')
		select 0 ord, left((select case when left(name,1) like ''[0-9]'' then '''' else  rtrim(code)+'' '' end +rtrim([name]) from dbo.DICTIONARY_DEPARTMENT where link=link_organization)+'' - ''+isnull((select [name] from dbo.KL_BUDG_TYPE A where A.link=link_type_svod),''''),254) as Org' 

insert #Exec (ExecStr, orders)
values(@varKScStr3, 310 )		

set @varKScStr3_1 =  '
,Link_Tree, Link_Tree_Self, childrens, FilterField
        into   #tabTable6       
		from dbo.[RA_SELECT_SVOD_FORMS](@iLINK_SAVED_FORM) RSF

    IF @tmp_table<>''''
     begin
        set @cExec=''SELECT * INTO ''+@tmp_table+'' FROM #tabTable6  ''
        execute(@cExec)
     end
     else   
        SELECT B.* FROM 
        dbo.[RA_SELECT_SVOD_FORMS2](@iLINK_SAVED_FORM) A
        INNER JOIN #tabTable6 B  ON A.Link_Tree = B.Link_Tree
        order by A.[level]

        DROP TABLE #tabTable6

END
END
ELSE
BEGIN
--удаление fcol
IF @varKSLSF > 0 BEGIN
SELECT checked=0,UPD=0,del=0,link_saved_form=@varKSLSF,'

insert #Exec (ExecStr, orders)
values(@varKScStr3_1, 600 )	

set @varKSRunStrF=''

select @varKSiVal_Type = val_type, @varKSLink_Code_Col = Link_Code_Col from report_tables where link_table = @iLINK_TABLE
IF @varKSiVal_Type = 0 
	set @varKSRunStrF = ' rr.link_row, rr.orders, rr.Calc_orders, rr.Print_Null,
isnull((select convert(char(100),formula) from report_formula RF where RF.link_row = RR.link_row and link_col = @varKScode_Col ),'''') as code'
ELSE 
	set @varKSRunStrF =  ' 0 as link_row, '+case when @order_rule<>'' then @order_rule_new else '0' end+' as orders, 0 as Calc_orders, 0 as Print_Null,
RR.Code_Row as code'

insert #Exec (ExecStr, orders)
values(@varKSRunStrF, 800 )

SET @varKScStr2F = ''

OPEN SEL_CURSOR
FETCH NEXT FROM SEL_CURSOR INTO @varKSLink_Col, @varKSOrders, @varKSname, @varKSiColType, @varKSiLen, @varKSiIsEdit
WHILE @@FETCH_STATUS = 0
BEGIN
	IF @varKSiLen<=0 and @varKSiColType=1
		set @varKSiLen=254
	set @varKScStr3F = ''
	IF @varKSiVal_Type = 0
	BEGIN /* Стандартные таблицы */
		IF @varKSiColType = 0
		BEGIN
			set @varKSRunStrF = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) + '= coalesce((select convert(numeric(20,' + convert(char(2),@varKSiLen) + '),summa) from '+ltrim(rtrim(@cTmpName))+'report_summa'+@cSuffix_table+' where link_saved_form = SF.link_saved_form and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' and Link_Row = RR.link_Row),0)'
		END
		ELSE
		BEGIN
			IF @varKSiIsEdit = 0
				set @varKSRunStrF = ',
isnull((select left(formula,'+ltrim(str(@varKSiLen))+') from report_Formula RF where link_col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and RF.link_row = RR.link_row ),'''') as col' + ltrim(convert(varchar(7),@varKSOrders))
			ELSE
				set @varKSRunStrF = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) + '= isnull((select convert(varchar(' + convert(char(4),@varKSiLen) + '),str_val) from report_string'+@cSuffix_table+' where link_saved_form = SF.link_saved_form and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' and Link_Row = RR.link_Row),'''')'
		END
		IF @varKSiIsEdit = 0
			set @varKScStr2F = ',
(select left(formula,'+ltrim(str(@varKSiLen))+') from report_formula RF where link_col =' + ltrim(convert(varchar(7),@varKSLink_Col)) + ' and RF.link_row = RR.link_row ) as col' + ltrim(convert(varchar(7),@varKSOrders))
		ELSE 
		BEGIN
			IF @varKSiColType = 0
				set @varKScStr2F = ',
convert (numeric(20,' + convert(char(2),@varKSiLen) + '),0) as col'+ ltrim(convert(varchar(7),@varKSOrders))
			ELSE
				set @varKScStr2F = ',
convert (VarChar(' + convert(char(4),@varKSiLen) + '),'''') as col'+ ltrim(convert(varchar(7),@varKSOrders))

		END

		IF @varKSiColType = 0
			set @varKScStr3F = ',
convert(numeric(20,' + convert(char(2),@varKSiLen) + '),coalesce((select summa  from '+ltrim(rtrim(@cTmpName))+'report_summa_all where link_row=@varKSLRow and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col)) +' and link_saved_Form = RSF.link_saved_Form),0)) as col' + ltrim(rtrim(convert(varchar(5),@varKSOrders)))
	END
	ELSE /* Для динамических таблиц */
	BEGIN
		IF @varKSiColType = 0
		BEGIN
			SET @varKSRunStrF = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) 
	+ '= convert(numeric(20,' + convert(char(2),@varKSiLen) 
	+ '),SUM(case when link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' then float_val else 0 end))'
			SET @varKScStr2F = ',
convert (numeric(20,' + convert(char(2),@varKSiLen) + '),0) as col'+ ltrim(convert(varchar(7),@varKSOrders))
	/* Переписать для расшифровки динамически сведеных таблиц */
			SET @varKScStr3F = ',
convert(numeric(20,' + convert(char(2),@varKSiLen) + '),coalesce((select float_val  from '+ltrim(rtrim(@cTmpName))+'REPORT_DINAMICS_ALL  where code_row=@varKScCodeRow and link_col=' + ltrim(convert(varchar(7),@varKSLink_Col)) +' and Link_SF = RSF.link_saved_Form),0)) as col' + ltrim(rtrim(convert(varchar(5),@varKSOrders)))
		END
		ELSE
		BEGIN
			IF @varKSiLen = 0
				SET @varKSiLen = 254
			IF @varKSLink_Code_Col = @varKSLink_Col
			BEGIN /* ключевой столбец */
				SET @varKSRunStrF = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) + '= RR.Code_Row '
				SET @varKScStr2F = ',
convert (VarChar(' + convert(char(4),@varKSiLen) + '),'''') as col'+ ltrim(convert(varchar(7),@varKSOrders))
			END
			ELSE
			BEGIN /* обычный текстовый столбец */
				SET @varKSRunStrF = ',
col'+ ltrim(convert(varchar(7),@varKSOrders)) 
	+ '= (convert(varchar(' + convert(char(4),@varKSiLen) 
	+ '),MAX(case when link_col=' + ltrim(convert(varchar(7),@varKSLink_Col))  + ' then str_val else '''' end)))'
				SET @varKScStr2F = ',
convert (VarChar(' + convert(char(4),@varKSiLen) + '),'''') as col'+ ltrim(convert(varchar(7),@varKSOrders))
			END
		END
	END

	insert #Exec (ExecStr, orders)
	values(@varKSRunStrF, 800 + @varKSOrders)		

	insert #Exec (ExecStr, orders)
	values(@varKScStr2F, 1000 + @varKSOrders)		

	insert #Exec (ExecStr, orders)
	values(@varKScStr3F, 1200 + @varKSOrders)		

	FETCH NEXT FROM SEL_CURSOR INTO @varKSLink_Col, @varKSOrders, @varKSname, @varKSiColType, @varKSiLen, @varKSiIsEdit
END

CLOSE SEL_CURSOR
DEALLOCATE SEL_CURSOR

IF @varKSiVal_Type = 0 
BEGIN
	set @col_ord_for_sort = 0
	select @col_ord_for_sort = isnull(orders,0) from dbo.report_coloumns where link_table = @iLINK_TABLE and ([property] & 8) > 0
	SET @varKSRunStr05F =',
itog = 0
INTO #tabTable1
FROM report_rows RR, report_saved_forms SF
WHERE RR.link_table =' + convert(varchar,@iLINK_TABLE) + '
AND SF.link_saved_form = @varKSLSF'+case when @is_dinamic=1 then 
' and (exists(select link_row from report_string'+@cSuffix_table+' RS where RS.link_saved_form=@varKSLSF and RS.link_row=RR.link_row)
or exists(select link_row from '+ltrim(rtrim(@cTmpName))+'report_summa'+@cSuffix_table+' RS where RS.link_saved_form=@varKSLSF and RS.link_row=RR.link_row))'
else '' end+'
ORDER by orders
IF @bDeleteEmptyRows = 1 EXEC dbo.[RA_DELETE_EMPTY_ROWS] ' + CAST(@varKSiVal_Type AS VARCHAR)+ ',''tabTable1''

IF @tmp_table<>''''
 begin
    set @cExec=''SELECT * INTO ''+@tmp_table+'' FROM #tabTable1 order by orders ''
    execute(@cExec)
 end
 else   
    SELECT * FROM #tabTable1 order by '+ case @col_ord_for_sort when 0 then 'orders' else 'col'+cast(@col_ord_for_sort as varchar) end+'
 
    DROP TABLE #tabTable1

END
ELSE 
    IF @varKSLSF = 0 
	SELECT  0 as checked,  0 as UPD, 0 as del, @varKSLSF as link_saved_form, rr.link_row, rr.orders, rr.Calc_orders, rr.Print_Null,
(select convert(char(100),formula) from report_formula RF where RF.link_row = RR.link_row and link_col = @varKScode_Col ) as code'
	
SET @varKScStr2F = ',
itog = 0
	FROM report_rows RR 
	WHERE RR.link_table =' + convert(varchar,@iLINK_TABLE)+case when @is_dinamic=1 then ' and 1 = case when @all_str=0 then 0 else 1 end' else '' end+'
	ORDER by orders'
END
ELSE 
BEGIN
	set @col_ord_for_sort = 0
	select @col_ord_for_sort = isnull(orders,0) from dbo.report_coloumns where link_table = @iLINK_TABLE and ([property] & 8) > 0
	SET @varKSRunStr05F = '
   INTO #tabTable1
	FROM (select RD.* from (select distinct Code_Row, Link_SF from '+ltrim(rtrim(@cTmpName))+'report_dinamics'+@cSuffix_table+' RD  inner join report_coloumns RC on RD.Link_SF = @varKSLSF and RD.Link_Col = RC.Link_Col and RC.Link_Table = ' + convert(varchar,@iLINK_TABLE) + ') RR
		left join '+ltrim(rtrim(@cTmpName))+'report_dinamics'+@cSuffix_table+' RD  on RD.Link_SF = RR.Link_SF and RR.Code_Row = RD.Code_Row 
        where RD.Link_SF=@varKSLSF) RR
	group by RR.Code_Row
	order by RR.Code_Row

  IF @bDeleteEmptyRows = 1
   BEGIN
      EXEC dbo.[RA_DELETE_EMPTY_ROWS] ' + CAST(@varKSiVal_Type AS VARCHAR)+ ',''tabTable1''
   END

    IF @tmp_table<>''''
     begin
        set @cExec=''SELECT * INTO ''+@tmp_table+'' FROM #tabTable1 order by orders, code ''
        execute(@cExec)
     end
     else   
        SELECT * FROM #tabTable1 order by '+ case @col_ord_for_sort when 0 then 'orders, code' else 'col'+cast(@col_ord_for_sort as varchar) end+'

   DROP TABLE #tabTable1
END
ELSE
    IF @varKSLSF = 0 
	SELECT  0 as checked,  0 as UPD, 0 as del, @varKSLSF as link_saved_form, 0 as link_row, 0 as orders, 0 as Calc_orders, 0 as Print_Null,

convert(varchar(100),'''') as code'

	SET @varKScStr2F = '
	FROM I_REPORT_DINAMIC_ROWS RR
	WHERE RR.link_SF = @varKSLSF
		and RR.link_table = ' + convert(varchar,@iLINK_TABLE) + '
'
END

insert #Exec (ExecStr, orders)
values(@varKSRunStr05F, 900)		

insert #Exec (ExecStr, orders)
values(@varKScStr2F, 1100 )		

IF @varKSiVal_Type = 0 
	set @varKScStr3F_1 = '
	ELSE 
	BEGIN
		set @varKSLRow = - @varKSLSF
		select @varKSLTable = link_table from report_rows where link_row = @varKSLRow
	
		select @varKSLForm = link_Form from report_tables where link_table = @varKSLTable
		select @varKScCode = code from report_forms where link_form = @varKSLForm
		select 0 ord,left((select case when left(name,1) like ''[0-9]'' then '''' else  rtrim(code)+'' '' end +rtrim([name]) from dbo.DICTIONARY_DEPARTMENT where link=link_organization)+'' - ''+isnull((select [name] from dbo.KL_BUDG_TYPE A where A.link=link_type_svod),''''),254) as Org' 
ELSE  /* расшифровка для динамических таблиц */
	set @varKScStr3F_1 = '
	ELSE 
	BEGIN
	select @varKScCode = code from report_forms where link_form = (select max(link_Form) from report_tables where link_table = ' +ltrim(rtrim(convert(varchar(10), @iLINK_TABLE))) + ')
		select 0 ord,left((select case when left(name,1) like ''[0-9]'' then '''' else  rtrim(code)+'' '' end +rtrim([name]) from dbo.DICTIONARY_DEPARTMENT where link=link_organization)+'' - ''+isnull((select [name] from dbo.KL_BUDG_TYPE A where A.link=link_type_svod),''''),254) as Org'

	set @varKScStr3F = '
	,Link_Tree, Link_Tree_Self, childrens, FilterField
        into   #tabTable5       
		from dbo.[RA_SELECT_SVOD_FORMS](@iLINK_SAVED_FORM) RSF

    IF @tmp_table<>''''
     begin
        set @cExec=''SELECT * INTO ''+@tmp_table+'' FROM #tabTable4  ''
        execute(@cExec)
     end
     else   
        SELECT * FROM #tabTable4 

        SELECT B.* FROM 
        dbo.[RA_SELECT_SVOD_FORMS2](@iLINK_SAVED_FORM) A
        INNER JOIN #tabTable4 B  ON A.Link_Tree = B.Link_Tree
        order by A.[level]

        DROP TABLE #tabTable4


END


END

'
 
insert #Exec (ExecStr, orders)
values(@varKScStr3F_1, 1110)		
 
insert #Exec (ExecStr, orders)
values(@varKScStr3F, 1400)	

declare @cTMP varchar(8000), @itmp int
declare @cTMPF varchar(8000), @itmpF int

set @itmp = PATINDEX('%itog %', @varKSRunStr05)
set @cTMP = ''
if @itmp > 0
begin
	SET @cTMP = RIGHT(@varKSRunStr05, LEN(@varKSRunStr05) - @itmp + 4 )
	set @varKSRunStr05 = LEFT(@varKSRunStr05, @itmp - 4)
end

set @itmpF = PATINDEX('%itog %', @varKSRunStr05F)
set @cTMPF = ''
if @itmpF > 0
begin
	SET @cTMPF = RIGHT(@varKSRunStr05F, LEN(@varKSRunStr05F) - @itmpF + 4 )
	set @varKSRunStr05F = LEFT(@varKSRunStr05F, @itmpF - 4)
end

IF @iType=0
	begin
		declare @StatCodeForm varchar(100)
		select @StatCodeForm = RTRIM(RF.Code) + ' ' + LEFT(RT.Name, 40) from dbo.report_tables RT join dbo.report_forms RF on RT.link_form = RF.link_form
		where RT.link_table = @iLINK_TABLE
		set @varKSRunStr = 
'PROCEDURE ' + @varKSViewName + '
@varKSLSF	int,
@varKSpTYPE	int=1,
@varKSPNom	int=1,
@varKSpDATE	datetime=''01/01/2003'',
@varKScCodeRow	varchar(100)='''',
@iLINK_SAVED_FORM INT = NULL,
@bDeleteEmptyRows BIT = NULL,
@tmp_table varchar(100) = '''',
@del_fcol int=0,
@all_str int=0
AS
declare @Reads int , @time_begin datetime
set @time_begin = getdate()
--  Генератор I_REPORT_CREATE_PROC
if exists(select * from report_saved_forms where link_saved_form=@varKSLSF and is_arhiv=1) 
	exec '+@varKSViewName+'_ARH @varKSLSF,@varKSpTYPE,@varKSPNom,@varKSpDATE,@varKScCodeRow,@iLINK_SAVED_FORM,@bDeleteEmptyRows,@tmp_table,@del_fcol,@all_str
else	
	exec '+@varKSViewName+'_OPER @varKSLSF,@varKSpTYPE,@varKSPNom,@varKSpDATE,@varKScCodeRow,@iLINK_SAVED_FORM,@bDeleteEmptyRows,@tmp_table,@del_fcol,@all_str
	set @Reads = @@ROWCOUNT
--	if ISNULL((select Val_Int from dbo.report_options where razdel = ''statistics'' and code = ''mode''), 0) = 1 
--		insert dbo.report_statistics (Operation, CodeForm, Reads, Duration) values (4, ''' + @StatCodeForm + ''', @Reads,  getdate() - @time_begin)
'
	
	IF Object_id (@varKSViewName) is not null
	    BEGIN
		  	execute('ALTER ' + @varKSRunStr)
    	END   
   ELSE
  		execute('CREATE ' + @varKSRunStr )
	set @varKSRunStr = 'GRANT EXECUTE ON ' + @varKSViewName + ' TO PUBLIC'

	EXECUTE (@varKSRunStr)
    exec I_REPORT_CREATE_PROC @iLINK_TABLE,'',1
	exec I_REPORT_CREATE_PROC @iLINK_TABLE,'',2
	exec I_REPORT_CREATE_PROC @iLINK_TABLE,'#',3
	end
else
begin
	IF Object_id (@varKSViewName) is not null
   BEGIN
		insert #Exec (ExecStr, orders)
		values('ALTER ', 0)	
   END   
   ELSE
		insert #Exec (ExecStr, orders)
		values('CREATE ', 0)	

	exec ssp_execresultset 'select ExecStr from #Exec order by orders'

	set @varKSRunStr = 'GRANT EXECUTE ON ' + @varKSViewName + ' TO PUBLIC'
--	print @varKSRunStr
	EXECUTE (@varKSRunStr)
end
	set @varKSViewName = replace(@varKSViewName, 'dbo.', '')
	exec dbo.U_UPDATE_SCRIPT_PROPERTY @varKSViewName, 1, 'NOSCRIPT'

	drop table #Exec
END


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

/*
exec RI_PROC_T1867 5.768000000000000e+003
dbo.[I_REPORT_CREATE_PROC] 1867

select * from report_saved_forms 
select * from report_tables where link_form = 640

I_REPORT_CREATE_PROC_ON_SETUP

*/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),
		@iKbkLen int
---------------
				
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

if Year(@dCALC_DATE) < 2016
	set @iKbkLen = 17
else
	set @iKbkLen = 20

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), -- Признак платежа000
	[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) + '00000000000000000000',@iKbkLen) + 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,@iKbkLen - 10), -- ЦСР
	[COL9] = substring(rtrim(KBK),@iKbkLen - 2,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) + '00000000000000000000',@iKbkLen) + 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


ALTER TABLE [dbo].[REPORT_DINAMICS] ALTER COLUMN [Code_Row] varchar(100) NOT NULL 
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RI_REPORT_FORMULA_ALL_CALCULATE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RI_REPORT_FORMULA_ALL_CALCULATE]

GO

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

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

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

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

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

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

        exec(@cstr)
END

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

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

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


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

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

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

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

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

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


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

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

   set ansi_warnings OFF
   SET ARITHABORT OFF
   SET ARITHIGNORE OFF

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

set ansi_warnings ON
SET ARITHABORT ON
SET ARITHIGNORE ON



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

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

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

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

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

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

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

	   while @@fetch_status = 0
	   begin

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


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

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

		   end

		   else
			   set @ScriptStr = @ScriptStrF

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

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

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

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

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



GO


GRANT EXECUTE ON dbo.[RI_REPORT_FORMULA_ALL_CALCULATE] TO PUBLIC

GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*

	© Кейсистемс (Keysystems), 2006
	Редактирование/создание отчета/свода/свода сводов в WEB
*/

CREATE       PROCEDURE dbo.RN_SPLIT_CODE_ROW
    @lsf int, -- линк сохраненной формы
	@OrderTable tinyint = NULL -- порядковый номер таблицы
AS

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

   declare @code_form varchar(20),@link_form int,@date datetime, @linkTable_only int
   set @code_form=''
   select @date=start_date,@code_form=code,@link_form=link_form from report_forms where link_form=(select link_form from report_saved_forms where link_saved_form=@LSF)
   IF @code_form=''
		return
   --проведем расщепление code_row
   create table #code (link_col int,code_row varchar(100),str_val varchar(250)) 
   create table #tmp_code (link_col int,code_row varchar(100),str_val varchar(250)) 
   declare @link_col int,@link_table int,@script_str varchar(8000),@key varchar(1000),@i int,@count_col int,@cstr varchar(8000),@split varchar(1000)

	if @OrderTable is NOT NULL
		select @linkTable_only = Link_Table from report_tables where link_form = @link_form and orders = @OrderTable
   
   --сплит по новому	
   IF exists(select * from report_tables where link_form=@link_form and charindex('SPLIT=',script_str)>0) 
	begin
		--
		declare @table_split table (link_table int,script_str varchar(8000)) 
		insert @table_split
		select link_table,script_str from report_tables where link_form=@link_form and charindex('SPLIT=',script_str)>0 
			and (Link_Table = @linkTable_only or @OrderTable is NULL) -- добавлено Olga 2009.10.05 для импорта
		while exists(select * from @table_split)
			begin
				select top 1 @link_table=link_table,@script_str=script_str from @table_split
				exec rn_get_formula_code_row @link_Table,'SPLIT=',@key output
				--расшифровка
				set @key=replace(@key,'SPLIT=','')
				set @count_col=dbo.rn_getwordcount(@key,'#')
				set @i=1
				while @i<=@count_col
					begin
						set @split=dbo.rn_getwordnum(@key,@i,'#')
						select @link_col=link_col from report_coloumns where link_table=@link_table and orders=cast(replace(upper(dbo.rn_getwordnum(@split,1,'=')),'COL','') as int)
						--print @key
						--print @split
						set @split=replace(@split,dbo.rn_getwordnum(@split,1,'=')+'=','')
						set @cstr='insert #tmp_code (link_col,code_row,str_val)
						select distinct '+str(@link_col)+',code_row,'+@split+' from report_dinamics where link_sf='+str(@lsf)+' and link_col in (select link_col from report_coloumns where link_table='+str(@link_table)+')'
						--print @cstr
						SET @i=@i+1
						execute(@cstr)
					end
				delete  @table_split where link_table=@link_table
			end


	--запись данных
    Create index #IX_tmp_code_new on #tmp_code (link_col,code_row)

    INSERT report_dinamics (link_sf,link_col,code_row,str_val)
    select @lsf,link_col,code_row,str_val from #tmp_code A where not exists(select * from report_dinamics B where B.link_sf=@lsf and B.link_col=A.link_col and A.code_row=B.code_row) group by link_col,code_row,str_val

    UPDATE report_dinamics 
    SET str_val=A.str_val
    from report_dinamics B ,#tmp_code A where B.link_sf=@lsf and B.link_col=A.link_col and A.code_row=B.code_row 

	return
	end

   IF @code_form like '0503169%' or @code_form like '0503369%'
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1
        --счет
       select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',1,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)


        --год
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,REPLACE(REPLACE(SUBSTRING(RTRIM(CODE_ROW)+'',10,4),'8888',''),'0000','') from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 


   IF @code_form in ('(72н)0503317G','(72н)0503317M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=2
        --adm расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=5
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=6
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',8,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ВР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=7
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',15,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЭКР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=8
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',18,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
     end 


   IF @code_form in ('(72н)0503152','0503152G')
     begin
        ----------------------- расходы --------------------------------------------------------
		select @link_table=link_table from report_tables where link_form=@link_form and orders=2
        --adm расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=5
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',8,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ВР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=6
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',15,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЭКР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=7
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',18,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

		----------------------- источники ------------------------------------------------------
        select @link_table=link_table from report_tables where link_form=@link_form and orders=3
        --Код строки
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000000000000',4,20) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 


   IF @code_form in ('(72н)0503182M')
   BEGIN
      select @link_table=link_table from report_tables where link_form=@link_form and orders=3
      
      --Код строки
      select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
      insert #tmp_code (link_col,code_row,str_val)
      select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'000',1,3) 
      from report_dinamics 
      where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

      --Источники
      select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
      insert #tmp_code (link_col,code_row,str_val)
      select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
      
   
   END
   
   IF @code_form in ('(72н)0503317M','(72н)0503314M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=3
        --Код строки
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000000000000',4,20) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 

   IF @code_form in ('(72н)0503151','0503151G','(72н)0503124','(72н)0503127M','(72н)0503117M','(72н)0503137M','(72н)0503114M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=3
        --Код строки
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000000000000',4,17) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 

   IF @code_form = ('(72н)0503110')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1
        --adm 
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1 -- таблица доходы
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --Дохгр
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',4,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --код счета
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',7,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_table=link_table from report_tables where link_form=@link_form and orders=2 -- таблица расходы
        --adm 
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --РзПр
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --код счета
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',8,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_table=link_table from report_tables where link_form=@link_form and orders=3 -- таблица источники
        --adm 
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --РзПр
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --код счета
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000',8,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
     end 


   IF @code_form in ('(72н)425M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1
        --adm 
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --okato
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'                               ',4,8) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --элемент бюджета
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'                                ',12,2) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --код счета
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=5
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'                                                       ',14,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --счет
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=8
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'                                                       ',23,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
     end 

   IF @code_form in ('РРО1')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'       ',1,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'         ',8,9) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=18
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'000',17,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
     end 

   IF @code_form in ('(90н)581')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1
        --код организации 
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'                ',6,10) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table) /*and Code_Row not like '_____ИТОГО%' */and Code_Row not like '_____ВСЕГО%'
    end

   IF @code_form in ('(72н)0503151','0503151G','(72н)0503124','(72н)0503117','(72н)0503127','(72н)0503137','(72н)0503114','(72н)0503117M','(72н)0503127M','(72н)0503137M','(72н)0503114M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=2

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',1,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',5,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ВР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=5
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',12,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЭКР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=6
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',15,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
     end 

   IF @code_form in ('(72н)0503164','(72н)0503179G','(72н)0503164M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=2

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',1,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',5,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 

   IF @code_form in ('(72н)0503179G')
   BEGIN     
        select @link_table=link_table from report_tables where link_form=@link_form and orders=3
         
        --Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000000000000',4,17) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)
   END

   IF @code_form in ('(72н)0503364M','(72н)0503364Mf')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=2

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',1,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',5,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 



   IF @code_form in ('(72н)0503164M')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=3

       --Код строки
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'0000000000000000000000000',4,8) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 




   IF @code_form in ('(72н)0521443') 
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1

        -- расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',1,20) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        -- расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',22,20) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 
                                                                                             
   IF @code_form like '(72н)0503169%' --or @code_form like '%0503369%' --or @code_form like '0503169G%'
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1

        --счет
       select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,REPLACE(SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000',1,9),'888888888','Всего задолженности:') from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)


        --год
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,REPLACE(REPLACE(SUBSTRING(RTRIM(CODE_ROW)+'',10,4),'8888',''),'0000','') from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

     end 


   IF @code_form like '(72н)410%'
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=1
        -- Доходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',1,17) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',18,6) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',24,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_table=link_table from report_tables where link_form=@link_form and orders=2
        -- Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',1,17) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',18,6) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',24,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_table=link_table from report_tables where link_form=@link_form and orders=3
        -- Источники
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=1
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',1,17) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=2
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',18,6) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000000000000000000000000',24,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)



     end 


   IF @code_form in ('(72н)0521429M','(72н)0521429')
     begin
        select @link_table=link_table from report_tables where link_form=@link_form and orders=3
        --adm расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=5
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',8,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ВР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=6
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',15,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЭКР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=7
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',18,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)



        select @link_table=link_table from report_tables where link_form=@link_form and orders=4
        --adm расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=3
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',1,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --РЗПР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=4
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',4,4) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЦСТ расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=5
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',8,7) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ВР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=6
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',15,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)

        --ЭКР расходы
        select @link_col=link_col from report_coloumns where link_table=@link_table and orders=7
        insert #tmp_code (link_col,code_row,str_val)
        select distinct @link_col,code_row,SUBSTRING(RTRIM(CODE_ROW)+'00000000000000000000',18,3) from report_dinamics where link_sf=@lsf and link_col in (select link_col from report_coloumns where link_table=@link_table)


     end 


--запись данных
    Create index #IX_tmp_code on #tmp_code (link_col,code_row)
   


    INSERT report_dinamics (link_sf,link_col,code_row,str_val)
    select @lsf,link_col,code_row,str_val from #tmp_code A where not exists(select * from report_dinamics B where B.link_sf=@lsf and B.link_col=A.link_col and A.code_row=B.code_row) group by link_col,code_row,str_val

    UPDATE report_dinamics 
    SET str_val=A.str_val
    from report_dinamics B ,#tmp_code A where B.link_sf=@lsf and B.link_col=A.link_col and A.code_row=B.code_row 

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

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


/*
c Кейсистемс (Keysystems), 2006
Расчет итогов для отчета (досчет), формулы берутся из КС
20060817 доступ к колонке
*/
CREATE              PROCEDURE dbo.RO_CALCULATE_DOSCHET
  @LSF  int,
  @cTables varchar(1000) = '',
  @cProgressTable     varchar(254)  = ''
AS

EXEC RN_CALCULATE_DOSCHET @LSF,@cTables,@cProgressTable
return 
declare @LinkForm int, @linkRule int, @ExecProc varchar(300), @OrderRow int, @ordersRule int, @i int,@nprecision float(10)
set @nprecision=0.001

select @LinkForm = Link_Form from dbo.report_saved_forms where Link_Saved_Form = @LSF
if @LinkForm is NULL
  return  -1

create table #Rules (link_rule int, order_rule int)
--declare @t_KS table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(100), Factor float(53), Exec_Proc varchar(250), Exec_Proc_Desc varchar(250), Value float(53), orders varchar(250))
declare @t_KS_V table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(100), [Rows] varchar(250), Cols varchar(250), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Filter varchar(250), Mask varchar(250), Value float(53), orders varchar(250), Filter_Desc varchar(250), Mask_Desc varchar(250),isLeftPart int) 
declare @t_temp table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(100), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value float (53), orders varchar(250))
declare @t_tmp table (lc int, lr int, lrule int, V float(53), o varchar(250), s char(2), cr varchar(100))
create table #t_sum (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(100), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value float (53), orders varchar(250))
create table #t_znak_not_plus (Link_Rule int, Orders varchar(250))
--create table  @t_Col table (Link_Col int primary key, Name varchar(254), Link_Table int, Val_Len tinyint)

create table #t_KS (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(100), [Rows] varchar(250), Cols varchar(250), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Filter varchar(250), Mask varchar(250), Value float(53), orders varchar(250), Filter_Desc varchar(250), Mask_Desc varchar(250),isLeftPart int ) 
create table #t_Col (Link_Col int primary key, Name varchar(254), Link_Table int, Val_Len tinyint, OrderCol tinyint)
create table #ListForms (lsf int, linkForm int, codeForm char(20), startDate datetime)

declare @strProgressExec varchar(1000)

insert #ListForms
    select link_saved_form, link_form, '', NULL from report_saved_forms where  Link_saved_form = @LSF 


select *
INTO #REPORT_FORMS
from REPORT_FORMS WITH (NOLOCK)
where link_form = (select linkform from #ListForms)



select *
into #report_tables
from dbo.report_tables WITH (NOLOCK)
where link_form in (select link_form from #REPORT_FORMS)

select *
into #REPORT_COLOUMNS
from dbo.REPORT_COLOUMNS WITH (NOLOCK)
where link_table in (select link_table from #report_tables)


if (select Code from #report_forms where Link_Form = @LinkForm) like '428%'
begin
  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000120', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000120' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000151', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000151' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00085000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00085000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00079000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00079000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00096000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00096000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000000' and Link_SF = @LSF)


  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00090000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00090000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00050000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00050000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00070000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00070000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000710', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000710' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000810', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000810' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000500', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000500' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000600', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000600' and Link_SF = @LSF)

end

if (select Code from #report_forms where Link_Form = @LinkForm) like '428'
begin
  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000251', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000251' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000540', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000540' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000640', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000640' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000231', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000231' and Link_SF = @LSF)
end 

-- колонки, которые можно загрузить из справочника, для динамических таблиц

IF @cTables=''
BEGIN
        declare cur_Table cursor local static forward_only
        for select orders from #report_tables where Link_Form = @LinkForm and Val_Type = 1
END
ELSE
BEGIN
        declare cur_Table cursor local static forward_only
        for select orders from #report_tables rt where rt.Link_Form = @LinkForm and rt.Val_Type = 1 and exists(select * from #iTables IT where IT.link_Table=rt.Link_table)
END
declare @OrderTable int 

open cur_Table
fetch next from cur_Table
into @OrderTable

while @@fetch_status = 0
begin
  exec dbo.RO_IMPORT_WITH_DICT @LSF, @orderTable
  fetch next from cur_Table
  into @OrderTable
end

close cur_Table
deallocate cur_Table

SELECT RR.*,RSV.Formula code 
into #I_REPORT_ROWS
FROM Report_Rows RR WITH (NOLOCK) LEFT JOIN 
  Report_Formula  RSV WITH (NOLOCK)
    ON  link_col IN (select link_code_col from #report_tables)
        AND RSV.link_row=RR.link_row
where link_table in (select link_table from #report_tables)

select *
into #i_report_dinamic_rows
from dbo.i_report_dinamic_rows WITH (NOLOCK)
where link_SF in (select lsf from #ListForms)

select *
into #REPORT_CONTROL_RULES
From REPORT_CONTROL_RULES WITH (NOLOCK)
where link_form in (select link_form from #REPORT_FORMS)

select *
into #REPORT_SUMMA
From REPORT_SUMMA WITH (NOLOCK)
Where Link_Saved_Form in (select lsf from #ListForms) AND Summa<>0

select *
into #REPORT_DINAMICS
From REPORT_DINAMICS WITH (NOLOCK)
Where Link_SF in (select lsf from #ListForms) and Float_val<>0


if (select Code from #report_forms where Link_Form = @LinkForm) like '428%'
begin
  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000120', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000120' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000151', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000151' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00085000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00085000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00079000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00079000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00096000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00096000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000000' and Link_SF = @LSF)


  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00090000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00090000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00050000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00050000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00070000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00070000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000710', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000710' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000810', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000810' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000500', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000500' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000600', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000600' and Link_SF = @LSF)

end

if (select Code from #report_forms where Link_Form = @LinkForm) like '428'
begin
  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000251', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000251' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000540', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000540' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000640', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000640' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000231', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000231' and Link_SF = @LSF)
end 

  insert #t_Col (Link_Col, Name, Link_Table, Val_Len, OrderCol)
      select RC.Link_Col, RC.Name, RC.Link_Table, RC.Val_Len, RC.orders
      from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table and RC.Col_Type = 0
      inner join #ListForms LF on RT.Link_Form = LF.LinkForm


if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Получение списка правил для формы'', percents = 10'
    execute(@strProgressExec)
end

-- получаем правила
insert into #Rules exec dbo.I_CONTROL_RULES_LIST @LSF, 0,default,default,default,1
declare @t_Rules table (Link_Rule int)

--insert @t_Rules
--select Link_Rule from #report_control_rows Ro left join #i_report_dinamic_rows RD on RD.Link_SF = @LSF and Ro.Code_Row = RD.Code_Row and RD.Link_Table = Ro.Link_Table
--    where Val_Type < 3 or RD.Code_Row is not NULL or RTRIM(ISNULL(Ro.Code_Row,'')) = '' or [sign] = '^'
--select * from @t_Rules
--return 

Create index #IX_REPORT_SUMMA on #report_summa (link_col,link_row)
Create index #IX_T_KS on #T_KS (link_rule,orders)
Create index #IX_T_KS_ORDERROW on #T_KS (ORDERROW)
Create index #IX_report_dinamics on #report_dinamics (link_sf,code_row,link_col)



declare @link_form int
select  @link_form=linkform from #ListForms
declare @minDateUpdCache datetime,@maxDateModifyRule datetime
select  @minDateUpdCache=Min(Upd_date) FROM REPORT_CONTROL_ROWS_CACHE RC WITH (NOLOCK) WHERE Link_Rule in (select link_rule from #Rules)
set     @minDateUpdCache=isnull(@minDateUpdCache,'19900101')
select  @maxDateModifyRule=Max(Modify_Date) from #Report_control_rules

--если данные в кеше старые или их нет, обновим их
IF @minDateUpdCache<@maxDateModifyRule and not EXISTS(select * from JURNAL where tableName='KS_REFRESH_CASH' and  link_pk=@link_form)
        exec RN_KS_REFRESH_CASH @link_form

IF EXISTS(SELECT  link_rule FROM REPORT_CONTROL_ROWS_CACHE RC WITH (NOLOCK)
                   WHERE Link_Rule in (select link_rule from #Rules) and IsDoschet = 1)  AND not EXISTS(select * from JURNAL where tableName='KS_REFRESH_CASH' and  link_pk=@link_form)
BEGIN
--есть данные в кеш таблице. 
declare  @NRULES table  (Link_Rule int,Orders varchar(100),include int)
INSERT @NRULES
    SELECT Link_rule,orders,sum(
        case when RC.val_type in (1,4) then 1
             when RC.Exec_proc<>'' then 1
             else 0 end)      
        FROM REPORT_CONTROL_ROWS_CACHE RC WITH (NOLOCK)
        WHERE Link_Rule IN (select link_rule from #Rules) and IsDoschet = 1 Group By Link_Rule,orders

declare  @NRULES1 table  (Link_Rule int,Orders varchar(100),orderrule int,[ROWS] varchar (250))


INSERT @NRULES1 
        SELECT A.Link_Rule,A.Orders,B.orderrule,B.[rows] 
        FROM @NRULES A LEFT JOIN #REPORT_CONTROL_RULES B on A.link_rule=B.link_Rule
--        WHERE   include>0 or 
--                   EXISTS(select * from #report_summa RS,REPORT_CONTROL_ROWS_CACHE   RRC with (nolock) where RRC.link_rule=A.link_rule and RRC.orders=A.orders and RS.link_col=RRC.link_col and RS.link_Row=RRC.link_Row)  
--                OR EXISTS(select * from #report_dinamics RS,REPORT_CONTROL_ROWS_CACHE RRC with (nolock) where RRC.link_rule=A.link_rule and RRC.orders=A.orders  and RS.link_col=RRC.link_col )                       

INSERT #T_KS
    SELECT 
            RC.Link_Rule, RC.Calc_Orders, RC.OrderRow, RC.Val_Type, RC.SignAfter, RC.Link_Table, RC.Link_Col, RC.Link_Row, RTRIM(isnull(RC.Code_Row,'')), CASE when RT.val_type=0 then '' else A.[ROWS] end, '', RC.Factor, RC.Exec_Proc, RC.Exec_Proc_Desc, RC.Filter, RC.Maska, 0, RC.Orders, RC.Filter_Desc, RC.Maska_Desc,isLeftPart
        FROM @NRULES1 A,REPORT_CONTROL_ROWS_CACHE RC WITH (NOLOCK) LEFT JOIN REPORT_TABLES  RT (nolock) ON RC.link_table=RT.link_table
        WHERE RC.Link_Rule=A.Link_Rule AND RC.orders=A.orders


 --если досчитываем одну таблицу отчета - удаляем лишние правила     
  IF @cTables<>'' 
   DELETE FROM #t_KS WHERE Link_Rule in (SELECT Link_Rule FROM #t_KS TK WHERE not exists(select * from #iTables IT where TK.linkTable=IT.Link_table) and  TK.LinkTable is not NULL and TK.orderrow=1)

--для динамических таблиц, необходимо размножение по строкам
        IF EXISTS(select  RT.link_Table from #report_tables RT,#t_Col TC where RT.link_table=TC.link_table and RT.val_type=1)
            begin
                if @cProgressTable <>'' begin
                    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Размножение правил'', percents = 30'
                    execute(@strProgressExec)
                end
                exec dbo.RO_RAZMNOJ_KS 1 -- размножаем правила
            end
END
ELSE
BEGIN
        select *
        into #REPORT_CONTROL_ROWS
        From REPORT_CONTROL_ROWS WITH (NOLOCK)
        where link_form in (select link_form from #REPORT_FORMS)

        insert  #t_KS
        SELECT R1.Link_Rule, Calc_Orders, OrderRow, Val_Type, Sign, Link_Table, Link_Col, Link_Row, RTRIM(isnull(Code_Row,'')), R1.[Rows], R1.[Cols], Factor, Exec_Proc, Exec_Proc_Desc, R2.Filter, R2.Maska, 0, '', Filter_Desc, Maska_Desc,-1
        FROM #REPORT_CONTROL_RULES R1 left join #REPORT_CONTROL_ROWS R2 on r1.Link_Rule = r2.Link_Rule
        WHERE R1.Link_Rule in (select link_rule from #Rules) and IsDoschet = 1 

 --если досчитываем одну таблицу отчета - удаляем лишние правила     
  IF @cTables<>'' 
   DELETE FROM #t_KS WHERE Link_Rule in (SELECT Link_Rule FROM #t_KS TK WHERE not exists(select * from #iTables IT where TK.linkTable=IT.Link_table) and  TK.LinkTable is not NULL and TK.orderrow=1)

                if @cProgressTable <>'' begin
                    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Размножение правил'', percents = 30'
                    execute(@strProgressExec)
                end

   exec dbo.RO_RAZMNOJ_KS 1 -- размножаем правила


END
-- доступ по колонке
--delete #t_KS
--where Link_Rule in (select Link_Rule from #t_KS where OrderRow = 1 and LinkCol is NOT NULL and dbo.RO_AccessColByLink(LinkCol) <= 0)

--select * from #T_KS A where exists
--(select * from #t_ks B where B.coderow='20205600080000151' and B.orderrow=1 and B.link_rule=A.link_rule and B.orders=A.orders)
--order by link_rule,orders,coderow
--return 
if not exists(select count(*) from #t_KS)
begin
  return  0
end
--select * from #t_ks where link_rule=371040
--индексы
--удалим все ненужные правила. 
--delete from #t_ks 

if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Подготовка к вычислению'', percents = 35'
    execute(@strProgressExec)
end


-- подготовка к вычислению
declare @t_znak table (LinkR int, OrderRule int, ord varchar(250), LC int, LR int, CR varchar(100), ValType tinyint)
declare @t_minus table (Link_Rule int)
declare @t_summa table (LinkR int, ord varchar (250), summa float(53))
declare @t_Result table (LC int, LR int, s float(53), CR varchar(100), ValType tinyint)
declare @OrderRule int
create table #Val (val float(53))



insert @t_znak (LinkR, OrderRule, ord, LC, LR, CR, ValType)
  SELECT Link_Rule, OrderRule, orders, LinkCol, LinkRow, CodeRow, Val_Type
  FROM #t_KS B
  WHERE [sign] = '='

delete #t_KS
where [sign] = '='

delete #report_summa
from @t_Znak
where Link_Saved_Form = @LSF and Link_Col = LC and Link_Row = LR and ValType = 0

delete #report_dinamics
from @t_Znak where Link_SF = @LSF and Link_Col = LC and Code_Row = CR and ValType = 3

select distinct LC,LR,CR,ValType into #t_znakTMP from @t_znak 

-- левые части приравниваем нулю
update report_summa
set Summa = 0
from #t_ZnakTMP
where Link_Saved_Form = @LSF and Link_Col = LC and Link_Row = LR and ValType = 0

update report_dinamics
set Float_Val = 0
from #t_ZnakTMP
where Link_SF = @LSF and Link_Col = LC and Code_Row = CR and ValType = 3
--для простых правил используем быстрое вычисление.
  
--select * from #t_ks
--select * from #t_ks where sign not in ('+','-','=')  or  val_type in (2)

if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Расчет итогов'', percents = 40'
    execute(@strProgressExec)
end

--SELECT * FROM #t_znakTMP WHERE cr='20000000000000000' ORDER BY lc

IF not EXISTS(select * from #t_ks where sign not in ('+','-','=') or  val_type in (2))  
begin
   --добавим итоговые ячейки в report_summa, report_dinamics
        insert #report_summa
          SELECT DISTINCT @LSF,LC,LR,0
          FROM #t_znakTMP where valType=0
        insert #report_dinamics
          SELECT DISTINCT @LSF,LC,CR,0,''
          FROM #t_znakTMP where valType=3
   --сдвиг  знаков 
--SELECT * FROM  #report_dinamics WHERE CODE_ROW='20000000000000000' ORDER BY CODE_ROW

   insert @t_minus
   select distinct link_rule from #t_ks where sign in ('-')

select link_rule,orderrow,sign into #sign FROM #T_KS A 
    where Exists(select * from @t_minus E where E.link_rule=A.link_rule) group by link_rule,orderrow,sign 

update #t_ks
    set [sign]=isnull(A.SIGN,'+')
    FROM   #T_KS D LEFT HASH JOIN #SIGN  A ON A.link_rule=D.link_rule AND  D.OrderRow = A.OrderRow +1 
    where Exists(select * from @t_minus E where E.link_rule=D.link_rule)

--   UPDATE #T_KS
--   SET [sign] = case when E.sign not in ('+','-') then '+' else E.sign end 
--    from #T_KS A,(select distinct isnull((select top 1 sign  from #t_ks C where A.link_rule=C.link_rule and A.orderrow-1=C.orderrow),'+')  sign  ,     
--             link_rule,orderrow FROM #T_KS A  where exists (select * from @t_minus B where B.link_rule=A.link_rule and A.orderrow in (B.orderRow,B.orderRow+1))) E
--           where A.link_rule=E.link_rule and A.orderrow=E.orderrow

     

--для констан проставим lin_col,link_row
--select * from #t_ks order by link_rule
   create table #value (link_rule int,orders varchar(100),Nsumma float(53))


--select * from #value where coderow='20205600080000151'
--select C.* from #t_ks where exists( C LEFT JOIN @T_ZNAK D ON C.Link_rule=D.linkR AND C.orders=D.ord
--        where  C.Nsumma<>0 and D.CR='20205600080000151'

   UPDATE #T_KS
       SET  linkcol=(select top 1 LC from @t_znak where  valtype in (0,3)) , linkrow=(select top 1 LR from @t_znak where valtype in (0)),codeRow=(select top 1 CR from @t_znak where valtype in (3))
       WHERE #T_KS.val_type=1 
--   вычисляем     
     Declare @CalcOrders int,@li int, @maxI int
     declare @t_order table (linkOrder int identity(1,1),OrderRule int)
     INSERT @t_order
     select  distinct OrderRule from #t_ks order by OrderRule 
     set @maxI=@@ROWCOUNT
     set @li=1    
        
     WHILE @li<=@maxI
     BEGIN
       select  @CalcOrders =OrderRule from @t_order where linkOrder=@li
       delete from #value 
    
   Insert #value 
    select Link_rule,orders,sum(nsumma) nsumma from 
        (select A.Link_rule,A.orders,
        NSumma = SUM(
       CASE WHEN A.[sign] = '+' and  val_type=0 THEN RS.Summa 
            WHEN A.[sign] = '-' and  val_type=0 THEN -RS.Summa 
            WHEN A.[sign] = '+' and  val_type=1 THEN A.Factor
            WHEN A.[sign] = '-' and  val_type=1 THEN -A.Factor
              ELSE 0 END)
                from #report_summa RS LEFT HASH JOIN #T_KS A ON 
                        RS.link_col=A.linkcol and RS.link_row=A.linkrow and A.val_type in (0,1) and A.OrderRule=@calcOrders 
                        where RS.summa<>0
                group by link_rule,orders        
         union all
        select A.Link_rule,A.orders,
        NSumma = SUM(
       CASE WHEN A.[sign] = '+' THEN RS.Float_val
            WHEN A.[sign] = '-' THEN -RS.Float_val
            WHEN A.[sign] = '+' and  A.val_type=1 THEN A.Factor
            WHEN A.[sign] = '-' and  A.val_type=1 THEN -A.Factor
          ELSE 0 END)
                from #report_dinamics RS LEFT HASH JOIN #T_KS A ON 
                        RS.link_col=A.linkcol and RS.code_row=A.coderow and A.OrderRule=@calcOrders  and A.val_type in (3,1)
                        where RS.float_val<>0
                group by A.link_rule,A.orders) A Group by Link_rule,orders


    UPDATE #report_summa 
       SET [summa]=[NSUMMA]
        from (select * from #value) C LEFT JOIN @T_ZNAK D ON C.Link_rule=D.linkR AND C.orders=D.ord
       where C.Nsumma<>0 and #report_summa.link_col=D.LC and #report_summa.link_row=D.LR

        UPDATE #report_dinamics
        SET [Float_val]=[NSUMMA]
        from (select * from #value) C LEFT JOIN @T_ZNAK D ON C.Link_rule=D.linkR AND C.orders=D.ord
        where  C.Nsumma<>0 and #report_dinamics.link_col=D.LC and #report_dinamics.code_row=D.CR

        set @li=@li+1
--select * from #report_dinamics where code_ROW='0009600000000000000'
    end
end
-----------------конец вычислений простых правил
else
begin

select @OrderRule = min(OrderRule) from @t_znak

update #t_KS
set OrderRow = OrderRow - 1

update #t_KS
set Exec_Proc = 'exec dbo.' + RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,')',' '),'(',' '))) + ', ' + LTRIM(STR(@LSF))
where val_type = 2
while exists(select top 1 * from @t_znak)
begin
  insert @t_KS_V
  select * from #t_KS where OrderRule = @OrderRule
  -- ВЫЧИСЛЕНИЕ VALUE - ЛИБО ЯЧЕЙКА, ЛИБО КОНСТАНТА, ЛИБО РЕЗУЛЬТАТ ВЫПОЛНЕНИЯ ПРОЦЕДУРЫ
  update @t_KS_V
  set Value = case when Val_Type = 0 then isnull((select round(summa, Val_Len) from #report_summa RS left join #report_coloumns RC on RS.Link_Col = RC.Link_Col where Link_Saved_Form = @LSF and RS.link_Col = LinkCol and Link_Row = LinkRow),0) 
      when Val_Type = 1 then isnull(Factor, 0) 
      when Val_Type = 3 then isnull((select round(float_val, Val_Len) from #t_Col RC inner loop join #report_dinamics RD on RD.Link_Col = RC.Link_Col where Link_SF = @LSF and RD.Link_Col = LinkCol and Code_Row = CodeRow), 0)
    end
--  select * from @t_KS_V
  declare Cur1 cursor static local
    for select Link_Rule, OrderRow, Exec_Proc, orders from @t_KS_V where LEN(RTRIM(ISNULL(Exec_Proc, ''))) > 0 and Val_Type = 2
  open Cur1
  fetch next from Cur1
  into @linkRule, @OrderRow, @ExecProc, @ordersRule
  while @@fetch_status = 0
  begin
    insert #Val execute(@ExecProc)
    update @t_KS_V set Value = isnull(val,0) from #Val where Link_Rule = @LinkRule and OrderRow = @OrderRow and orders = @OrdersRule
    delete #Val
    fetch next from Cur1
    into @linkRule, @OrderRow, @ExecProc, @ordersRule
  end
  close Cur1
  deallocate Cur1
  ----------
  -- ВЫЧИСЛЕНИЕ ВЫРАЖЕНИЯ
  insert #t_znak_not_plus
  select distinct Link_Rule, orders
  from @t_KS_V B where sign <> '+'

  insert #t_sum
  select Link_Rule, OrderRule, 1 as OrderRow, 0 as Val_Type, '+' as Sign, NULL as LinkTable, NULL as LinkCol, NULL as LinkRow, '' as CodeRow, 0 as Factor, ' ' as Exec_Proc, ' ' as Exec_Proc_Desc, sum(Value) as Value, orders
  from @t_KS_V A
  where not exists(select * from #t_znak_not_plus B where A.link_rule = B.link_rule and A.orders = B.orders)
  group by link_rule, OrderRule, orders

  delete @t_KS_V
--  from @t_KS_V K inner hash join (select distinct Link_rule from #t_sum) S on K.Link_Rule = S.Link_Rule
  from @t_KS_V K inner hash join #t_sum S on K.Link_Rule = S.Link_Rule
-- where link_rule in (select distinct Link_rule from #t_sum)

  set @i = 2
  while exists(select top 1 * from @t_KS_V where OrderRow > 1)
  begin
    insert @t_tmp (lc, lr, lrule, V, o, s, cr)
    select linkCol as lc, LinkRow as lr, Link_Rule as lrule, Value  as V, orders as o, sign as s, CodeRow from @t_KS_V where orderRow = @i

    
  /*  select @LSF, linkCol, linkRow, lc, lr, Value, V, sign, CodeRow, cr
    from @t_KS_V, @t_tmp A
    where OrderRow = 1 and link_rule = A.lRule and A.o = orders
*/
    update @t_KS_V
    set Value = dbo.ro_condition_eval_rule(@LSF, linkCol, linkRow, lc, lr, Value, V, sign, CodeRow, cr,@nprecision), sign = s, linkCol = lc, linkRow = lr, CodeRow = cr
    from @t_tmp A
    where OrderRow = 1 and link_rule = A.lRule and A.o = orders

    delete @t_tmp
    delete @t_KS_V where OrderRow = @i
    set @i = @i + 1
  end
  
  insert @t_KS_V (Link_Rule,OrderRule,OrderRow,Val_Type,Sign,LinkTable,LinkCol,LinkRow,CodeRow,Factor,Exec_Proc,Exec_Proc_Desc,Value,orders)
  select Link_Rule,OrderRule,OrderRow,Val_Type,Sign,LinkTable,LinkCol,LinkRow,CodeRow,Factor,Exec_Proc,Exec_Proc_Desc,Value,orders  from #t_sum

--  select * from  @t_KS_V

  insert @t_Result
  select LC, LR, Value, CR, ValType
  from @t_KS_V S inner hash join @t_znak Z on Z.LinkR = S.Link_Rule and Z.ord = S.orders and Z.OrderRule = @OrderRule

--  select * from @t_Result

  delete @t_Result where S = 0

  insert #report_summa (Link_Saved_form, Link_Col, Link_Row, Summa)
    select @LSF, LC, LR, max(S)
    from @t_Result R
    where ValType = 0 and LC is not NULL and LR is not NULL and not exists(select * from #report_summa S where Link_Saved_Form = @LSF and Link_Col = LC and Link_Row = LR)
    group by LC, LR
  
  update #report_summa
  set summa = s
  from @t_Result
  where ValType = 0 and link_saved_form = @LSF and Link_Col = LC and Link_Row = LR

  insert #report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val,str_val)
    select @LSF, LC, CR, max(S),''
    from @t_Result R
    where ValType = 3 and LC is not NULL and isnull(CR, '') <> '' and not exists(select * from #report_dinamics S where Link_SF = @LSF and Link_Col = LC and Code_Row = CR)
    group by LC, CR

  update #report_dinamics
  set Float_val = s
  from @t_Result
  where ValType = 3 and link_SF = @LSF and Link_Col = LC and Code_Row = CR

  
  delete @t_Znak where OrderRule = @OrderRule
  delete @t_KS_V
  delete @t_Summa
  delete @t_Result
  delete #t_sum
  delete #t_znak_not_plus
  select @OrderRule = min(OrderRule) from @t_znak
end

drop table #Rules
drop table #Val
drop table #t_sum
drop table #t_znak_not_plus

end

--сохраним данные из временных табличек

INSERT report_summa
select distinct RS.* from #report_summa RS,#t_znakTMP TZ
where RS.Link_Saved_Form = @LSF and RS.Link_Col = TZ.LC and RS.Link_Row = TZ.LR and TZ.ValType = 0
      and not exists(select * from report_summa S where S.Link_Saved_Form = @LSF and Link_Col = TZ.LC and Link_Row = TZ.LR) AND RS.summa<>0

update report_summa
set Summa = RS.Summa
from #report_summa RS,#t_znakTMP TZ
where (RS.Link_Saved_Form = @LSF and RS.Link_Col = TZ.LC and RS.Link_Row = TZ.LR and TZ.ValType = 0) 
       and report_summa.Link_Saved_Form=RS.Link_saved_form and report_summa.Link_Col=RS.Link_Col and report_summa.Link_Row=RS.Link_Row and RS.summa <>0
---------
--select * from  #report_dinamics order by link_col,code_row
--select * from report_dinamics where Link_SF = @LSF

--select RS.* from #report_dinamics RS,#t_znakTMP TZ
--where RS.Link_SF = @LSF and RS.Link_Col = TZ.LC and RS.Code_Row = TZ.CR and TZ.ValType = 3
--       and not exists(select * from report_dinamics S where S.Link_SF = @LSF and Link_Col = TZ.LC and Code_Row = TZ.CR) and RS.float_val<>0

--select RS.link_col,rs.code_row,count(*) from #report_dinamics RS,#t_znakTMP TZ
--where RS.Link_SF = @LSF and RS.Link_Col = TZ.LC and RS.Code_Row = TZ.CR and TZ.ValType = 3 group by RS.link_col,rs.code_row having count(*)>1 
----------
INSERT report_dinamics
select distinct RS.* from #report_dinamics RS,#t_znakTMP TZ
where RS.Link_SF = @LSF and RS.Link_Col = TZ.LC and RS.Code_Row = TZ.CR and TZ.ValType = 3
       and not exists(select * from report_dinamics S where S.Link_SF = @LSF and Link_Col = TZ.LC and RTRIM(Code_Row) = RTRIM(TZ.CR)) and RS.float_val<>0


update report_dinamics
set float_val=RS.Float_Val
from #report_dinamics RS,#t_znakTMP TZ
where RS.Link_SF = @LSF and RS.Link_Col = TZ.LC and RS.Code_Row = TZ.CR and TZ.ValType = 3
      and report_dinamics.link_sf=RS.link_sf and report_dinamics.link_col=RS.link_col and RTRIM(report_dinamics.code_row)=RTRIM(rs.code_row)  and RS.float_val<>0


if (select Code from #report_forms where Link_Form = @LinkForm) like '428%'
begin
  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000120', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000120' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00087000000000000151', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00087000000000000151' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00085000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 1 and not exists(select * from report_dinamics where Code_Row = '00085000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00079000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00079000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00096000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00096000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000000' and Link_SF = @LSF)


  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00090000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00090000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00050000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00050000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00070000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00070000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000710', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000710' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00057000000000000810', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00057000000000000810' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000000', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000000' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000500', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000500' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00008000000000000600', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 3 and not exists(select * from report_dinamics where Code_Row = '00008000000000000600' and Link_SF = @LSF)

end

if (select Code from #report_forms where Link_Form = @LinkForm) like '428'
begin
  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000251', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000251' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000540', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000540' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000640', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000640' and Link_SF = @LSF)

  insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
  select @LSF, Link_Col, '00097000000000000231', 0, ''
  from #report_coloumns RC inner join #report_tables RT on RC.Link_Table = RT.Link_Table 
    inner join report_saved_forms RSF on RSF.Link_Form = RT.Link_Form and RSF.Link_Saved_Form = @LSF
  where RC.orders = 5 and RT.orders = 2 and not exists(select * from report_dinamics where Code_Row = '00097000000000000231' and Link_SF = @LSF)
end 

-- колонки, которые можно загрузить из справочника, для динамических таблиц
if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Завершение расчета итогов'', percents = 90'
    execute(@strProgressExec)
end

--IF @cTables=''
--BEGIN
        declare cur_Table cursor local static forward_only
        for select orders from #report_tables where Link_Form = @LinkForm and Val_Type = 1
--END
--ELSE
--BEGIN
--        declare cur_Table cursor local static forward_only
--        for select orders from #report_tables rt where rt.Link_Form = @LinkForm and rt.Val_Type = 1 and exists(select * from #iTables IT where IT.link_Table=rt.Link_table)
--END

open cur_Table
fetch next from cur_Table
into @OrderTable

while @@fetch_status = 0
begin
  exec dbo.RO_IMPORT_WITH_DICT @LSF, @orderTable
  fetch next from cur_Table
  into @OrderTable
end

close cur_Table
deallocate cur_Table


--EXEC dbo.[RA_CALCULATE_KS_OUTSIDE] @LSF
GO
GRANT ALL ON dbo.[RO_CALCULATE_DOSCHET] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
c Кейсистемс (Keysystems), 2006
Расчет итогов для отчета (досчет), формулы берутся из КС
20060817 доступ к колонке
*/
CREATE           PROCEDURE dbo.RO_CALCULATE_INSIDE
  @LSF  int,
  @cTables varchar(1000) = '',
  @cProgressTable     varchar(254)  = '',
  @isWeb int = 0
AS
------------------------------------------------------------------------------
-- правила:
create table #t_Rules (Link_Rule int, Calc_orders int, algorithm tinyint, [sign_sr] char(2), cols varchar(250), [rows] varchar(1000), Str_Rule varchar(8000),  Comment varchar(2000), OrderRule INT, IsDoschet tinyint)
create table #t_Rules_region (Link_Rule int, orderRule int)
-- члены правила, используется для вычисления выражения:
create table #t_Row_KS (Link_Rule int, Calc_Orders int, OrderRow int, val_type tinyint, [sign] char(2), Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(100), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(250), part tinyint, algorithm tinyint, cols varchar(250), [rows] varchar(1000), [Value] float, orderCol tinyint default 0, CodeRow varchar(254) default '',cOrderTable varchar(254), cOrderCol varchar(10), [property] tinyint)
-- члены правила, используется для вычисления выражения:
create table #t_KS (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(100), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(250), part tinyint, algorithm tinyint, cols varchar(250), [rows] varchar(1000), [Value] float, orderCol tinyint default 0, CodeRow varchar(254) default '',cOrderTable varchar(254), cOrderCol varchar(10), px_comment varchar(254) default '', [property] tinyint)
-- левая часть
create table #t_KS_Left (Link_Rule int, val_type tinyint, Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(100), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(250), orderCol tinyint, CodeRow varchar(254), algorithm tinyint, cols varchar(250), [rows] varchar(1000))
-- записываем результат левой и правой частей:
create table #t_Result_C([Value] float, Link_Rule int, orderCol tinyint, CodeRow varchar(100), Link_Table int, Link_Col int, Link_Row int)

-- результат хранимок (хотя в будущем этого не надо)
create table #tmp (Value float)
-- для протокола операнды
--create table #t_Res_summand (Link_Rule int, OrderRow int, [sign] char(2), Code_Row varchar(100), [Value] numeric(20,4), orderCol tinyint default 0, CodeRow varchar(254) default '')
-- для размножения сложных правил
declare @t_temp table (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(100), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(250), part tinyint, algorithm tinyint, cols varchar(250), [rows] varchar(1000), [Value] float, orderCol tinyint default 0, CodeRow varchar(254) default '', cOrderTable varchar(254), cOrderCol varchar(10), px_comment varchar(254) default '', [property] tinyint)

-- для ускорения, чтобы уменьшить количество записей и не обращаться к постоянным таблицам
create table #t_Col (Link_Col int primary key, Name varchar(254), Link_Table int, Val_Len int, OrderCol tinyint, cOrderCol varchar(10))
create table #t_Rows_Static(Link_Row int primary key, Code varchar(100), Link_Table int, orders int)
create table #report_dinamics(Link_SF int, Code_Row varchar(100), link_col int, float_val numeric(20,4), str_val varchar(8000), Link_Table int)
create table #t_Summa(LSF int, link_col int, link_row int, Code varchar(100), summa float)
create table #t_Factor (Link_Rule int, OrderRow int, [sign] char(2), part tinyint, factor float)
create table #report_tables (Link_Table int, orders tinyint, Name varchar(254), Val_Type tinyint, Link_Code_Col int, Link_Form int)
-- Дерево КБК 
create table #TreeKBK (Link int, Link_Self int, Code_Row varchar(100), Link_Table int, Calc tinyint, cOrderTable varchar(300))
create table #TreeExclude (Code VARCHAR(100), Link_COl INT)

Create index #IX_REPORT_SUMMA on #t_summa (link_col,link_row)
Create index #IX_report_dinamics on #report_dinamics (link_col,code_row)
Create index #IX_report_dinamics_link_sf on #report_dinamics (link_table, link_col)

declare @cOrg varchar(254), @cBudg varchar(254), @LinkRule int, @ExecStr nvarchar(max),@ExecStr1 nvarchar(max), @IsSvod tinyint, @atr_code varchar(254), @i int, @maxOrderRow int, @orderTable int 
declare @nprecision float, @lsf_tmp int, @strProgressExec nvarchar(4000), @LinkF int, @codeForm varchar(20), @time_begin datetime, @time_end datetime, @cPeriod varchar(100), @CalcOrders int, @MaxCalcOrders INT
DECLARE @CodeRow VARCHAR(100), @dBeginDate DATETIME 
set @nprecision = 0.01


if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Получение данных отчетов'', percents = 3'
    exec sp_executesql @strProgressExec
end

if @cTables = '-1'
	set @cTables = ''

-------------------------------------------------------------------------------------------------------
-- получение данных 
select @LinkF = Link_Form, @dBeginDate = begin_date from report_saved_forms where link_saved_form = @LSF

exec dbo.ro_get_tree_kbk @LinkF, @cTables, @LSF -- грузим дерево КБК

insert #report_tables (Link_Table, orders, Name, Val_Type, Link_Code_Col, Link_Form)
select Link_Table, orders, Name, Val_Type, Link_Code_Col, Link_Form
from report_tables (NOLOCK)
where Link_Form = @LinkF

select * into #report_coloumns 
from report_coloumns RC (NOLOCK)
where Link_Table in (select Link_Table from #report_tables)

insert #t_Col (Link_Col, Name, Link_Table, Val_Len, OrderCol, cOrderCol)
select Link_Col, Name, Link_Table, Val_len, orders, ''
from #report_coloumns RC 
where Col_Type = 0 and dbo.RO_AccessColByLink(RC.Link_COl) > 0
if @isWeb = 1
begin
	delete #t_Col
	where exists(select top 1 * from report_saved_forms_permissions A where A.lsf=@LSF and A.link_col = #t_Col.Link_Col)
end
insert #t_Rows_Static(Link_Row, Code, Link_Table, orders)
select Link_Row, Code, Link_Table, orders
from i_report_rows 
where Link_Table in (select Link_Table from #report_tables where Val_Type = 0)

insert #t_summa (lsf, link_col, link_row, code, summa)
select RS.link_saved_form, RS.link_col, RS.link_row, R.code, RS.summa
from (select * from report_summa (NOLOCK) where Link_Saved_Form = @LSF)	RS inner join #t_Rows_Static R on RS.Link_Row = R.Link_Row

insert #report_dinamics (Link_SF, Code_Row, link_col, float_val, str_val, Link_Table)
select RD.Link_SF, RD.Code_Row, RD.link_col, RD.float_val, RD.str_val, C.Link_Table
from report_dinamics RD (NOLOCK) inner join #report_coloumns C on RD.Link_Col = C.Link_Col
where RD.Link_SF = @LSF --and C.Col_Type = 0

if @cProgressTable <>'' begin
	set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Получение правил досчета'', percents = 5'
	exec sp_executesql @strProgressExec
end

------------------------------------------------------------------------------------
-- получение правил
insert #t_Rules_region exec dbo.[I_CONTROL_RULES_LIST] @LSF, 0

insert #t_Rules (Link_Rule, Calc_orders, algorithm, [sign_sr], cols, [rows], Str_Rule, Comment, OrderRule, IsDoschet) 
select Ru.Link_Rule, Ru.Calc_orders, algorithm, sign_sr, REPLACE(cols,' ', ''), [rows], Str_Rule, Comment, Ru.OrderRule, Ru.[IsDoschet]
from report_control_rules Ru  (NOLOCK) inner join #t_Rules_region R on Ru.Link_Rule = R.Link_Rule
where isDoschet&1=1 --and Ru.Link_Rule = 2357895

truncate table #t_Rules_region


insert #t_Row_KS (Link_Rule, Calc_orders, OrderRow, val_type, [sign], Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], cOrderTable, cOrderCol, [property])
select Ro.Link_Rule, Calc_orders, Ro.OrderRow, Ro.val_type, Ro.[sign], Ro.Link_Table, Ro.Link_Col, Ro.Link_Row, Ro.Code_Row, Ro.Factor, Ro.px, Ro.Exec_Proc, Ro.Filter, coalesce(Ro.Filter_desc, Ro.Filter, ''), Ro.Maska, Ro.part, Ru.algorithm, REPLACE(Ru.cols,'-',''), Ru.[rows], '', '', [property]
from report_control_rows Ro (NOLOCK) inner join #t_Rules Ru on Ro.Link_Rule = Ru.Link_Rule


delete #t_Row_KS
where Link_Rule in (select Link_Rule from #t_Row_KS where Link_Col is NOT NULL and part = 0 and Link_Col not in (select Link_Col from #t_Col))


DELETE #t_Row_KS 
WHERE Link_rule IN (SELECT  r.link_rule  FROM  #t_Row_KS r JOIN dbo.report_control_rows ro ON r.[Link_Rule] = ro.link_rule AND r.[OrderRow] = ro.[OrderRow]
                   WHERE @dBeginDate <> ISNULL(ro.begin_date, @dBeginDate) AND r.Val_type IN (0, 3,4))     


declare @a_count int -- для динамических запросов

exec sp_executesql N'select @count = count(*) from #iTables', 
                   N'@count int output', @count = @a_count output


if isnull( @a_count,0)>0
begin
	delete #t_Row_KS where part = 0 and not exists(select top 1 * from #iTables T where T.Link_Table = #t_Row_KS.Link_Table) and Link_Table is NOT NULL

	delete #t_Row_KS
	where part = 1 and not exists(select top 1 * from #t_Row_KS R1 where R1.part = 0 and #t_Row_KS.Link_Rule = R1.Link_Rule)
end


--if not exists(select top 1 * from #t_Row_KS) 
--begin
--	drop table #t_Col
--	drop table #t_KS
--	drop table #t_KS_Left
--	drop table #t_Row_KS
--	drop table #t_Rules
--	drop table #t_Result_C
--	drop table #t_Rows_Static
--	drop table #tmp
--	drop table #report_dinamics
--	drop table #t_Summa
--	drop table #report_tables
--	return 0
--end

--update #t_KS set algorithm = 0 where algorithm = 4

update #t_Row_KS
set Exec_Proc = 'exec dbo.' + RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,')',' '),'(',' ')))  + ', ' + LTRIM(STR(@LSF))
where val_type = 2
/*update #t_Row_KS
set Exec_Proc = RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,']',')'),'[','('))) 
where val_type = 2
*/
select @MaxCalcOrders = max(Calc_Orders), @CalcOrders = min(Calc_orders) from #t_Rules
set @CalcOrders = isnull(@CalcOrders,0)
set @MaxCalcOrders = isnull(@MaxCalcOrders,-1)
if  @CalcOrders > 100
	exec dbo.RO_Tree_KBK_doschet @LSF

while @CalcOrders <= @MaxCalcOrders
begin
	--SELECT @CalcOrders
	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Расчет итогов №' + STR(@CalcOrders) + ''', percents = ' + convert(varchar(10), 5 + convert(int, @CalcOrders*90/(@MaxCalcOrders + 1) ))
		exec sp_executesql @strProgressExec
	END

	if  @CalcOrders = 100
		exec dbo.RO_Tree_KBK_doschet @LSF

	insert #t_KS (Link_Rule, OrderRow, val_type, [sign], Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], [Value], orderCol, CodeRow,cOrderTable, cOrderCol, [property])
	select Link_Rule, OrderRow, val_type, [sign], Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], [Value], orderCol, CodeRow,cOrderTable, cOrderCol, [property]
	from #t_Row_KS
	where Calc_Orders = @CalcOrders

	set @CalcOrders = @CalcOrders + 1

	set @a_count = 0
	exec sp_executesql N'select @count = count(*) from #t_KS', 
                   N'@count int output', @count = @a_count output

	if isnull(@a_count,0) = 0
		continue

	set @a_count = 0
	exec sp_executesql N'select @count = count(*) from #t_KS where algorithm in (0, 9)', 
                   N'@count int output', @count = @a_count output

	-----------------------------------------------------------------------------------------
	if isnull(@a_count,0) > 0
		exec dbo.RO_RAZMNOJ_KS_INSIDE 1 -- размножение правил для фильтров и знака '^' и сложных правил
	------------------------------------------------------------------------------------------
	insert #t_KS_Left (Link_Rule, val_type, Link_Table, Link_Col, Link_Row, Code_Row, Filter, Filter_desc, Mask, orderCol, CodeRow, algorithm, cols, [rows])
	select Link_Rule, val_type, Link_Table, Link_Col, Link_Row, Code_Row, Filter, Filter_desc, Mask, orderCol, CodeRow, algorithm, cols, [rows]
	from #t_KS
	where part = 0


	delete #t_KS where part = 0 
	delete #t_KS where not exists (select Link_Rule from #t_KS_Left L where L.Link_Rule = #t_KS.Link_Rule and isnull(L.orderCol, 0) = isnull(#t_KS.orderCol, 0) and isnull(L.CodeRow,'') = isnull(#t_KS.CodeRow,''))


	-- 	вычисляем
	-- обнуляем простые правила 
	update #t_Summa
	set summa = 0
	from (select * from #t_KS_Left where algorithm = 1 and Val_Type = 0) K
	where #t_Summa.Link_Col = K.Link_Col and #t_Summa.Link_Row = K.Link_Row
	
	update #report_dinamics
	set float_val = 0
	from (select * from #t_KS_Left where algorithm = 1 and Val_Type = 3) K
	where #report_dinamics.Link_Col = K.Link_Col and #report_dinamics.Code_Row = K.Code_Row

	-- простое правило
	insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
	select sum(case Val_Type 
					when 0 then case [sign] -- статическая таблица
							when '+' then case when K.[property] & 2 = 0 then isnull(S.summa,0)*px else isnull(abs(S.summa),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(S.summa ,0)*px else -isnull(abs(S.summa),0)*px end
						end 
					when 3 then  case [sign] -- динамическая таблица
							when '+' then case when K.[property] & 2 = 0 then isnull(D.float_val,0)*px else isnull(abs(D.float_val),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(D.float_val, 0)*px else -isnull(abs(D.float_val), 0)*px end
						end 
					when 1 then  case [sign] -- константа
							when '+' then K.Factor
							else -K.Factor
						end 
					else 0
				end), K.Link_Rule, orderCol, CodeRow
	from #t_KS K left join #t_summa S on S.Link_Col = K.Link_Col and S.Link_Row = K.Link_Row
		left join #report_dinamics D on D.Link_Col = K.Link_Col and D.Code_Row = K.Code_Row
	where algorithm = 1 
	group by Link_Rule, orderCol, CodeRow

	-----------------------------------------------------------------------------------------------------
	-- правило размножения для диапозона колонок 
	-- обнуляем
	update #t_Summa
	set summa = 0
	from #t_Summa S inner join #t_Col RC on S.Link_Col = RC.Link_Col, (select * from #t_KS_Left where algorithm = 2 and Val_Type = 0) K
	where S.Link_Row = K.Link_Row and (charindex(',' + rtrim(ltrim(str(RC.orderCol))) + ',', ','+cols+',') > 0 or cols = '')
	
	update #report_dinamics
	set float_val = 0
	from #report_dinamics S inner join #t_Col RC on S.Link_Col = RC.Link_Col, (select * from #t_KS_Left where  algorithm = 2 and Val_Type = 3) K
	where S.Code_Row = K.Code_Row and (charindex(',' + rtrim(ltrim(str(RC.orderCol))) + ',', ','+cols+',') > 0 or cols = '') and S.Link_Table = K.Link_Table

	
	insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
	select  sum(case Val_Type 
					when 0 then case [sign] -- статическая таблица
							when '+' then case when K.[property] & 2 = 0 then isnull(S.summa,0)*px else isnull(abs(S.summa),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(S.summa ,0)*px else -isnull(abs(S.summa),0)*px end
						end 
					when 3 then  case [sign] -- динамическая таблица
							when '+' then case when K.[property] & 2 = 0 then isnull(D.float_val,0)*px else isnull(abs(D.float_val),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(D.float_val, 0)*px else -isnull(abs(D.float_val), 0)*px end
						end 
					when 1 then  case [sign] -- константа
							when '+' then K.Factor
							else -K.Factor
						end 
					else 0
				end), Link_Rule, RC.orderCol, CodeRow
	from #t_KS K left join #t_summa S on S.Link_Row = K.Link_Row
		left join #report_dinamics D on D.Link_Table = K.Link_Table and D.Code_Row = K.Code_Row
		inner join #t_Col RC on isnull(S.link_col, D.link_col) = RC.link_col
	where algorithm = 2 and (charindex(',' + rtrim(ltrim(str(RC.orderCol))) + ',', ','+cols+',') > 0 or cols = '') and RC.orderCol is NOT NULL
	group by Link_Rule, RC.orderCol, CodeRow



	--------------------------------------------------------------------------------------------------------
	-- правило размножения для всех строк 
	-- обнуляем
	update #t_Summa
	set summa = 0
	from #t_Summa S, (select * from #t_KS_Left where algorithm = 3 and Val_Type = 0) K
	where S.Link_Col = K.Link_Col
	
	update #report_dinamics
	set float_val = 0
	from #report_dinamics S, (select * from #t_KS_Left where algorithm = 3 and Val_Type = 3) K
	where S.Link_Col = K.Link_Col

	insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
	select  sum(case Val_Type 
					when 0 then case [sign] -- статическая таблица
							when '+' then case when K.[property] & 2 = 0 then isnull(S.summa,0)*px else isnull(abs(S.summa),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(S.summa ,0)*px else -isnull(abs(S.summa),0)*px end
						end 
					when 3 then  case [sign] -- динамическая таблица
							when '+' then case when K.[property] & 2 = 0 then isnull(D.float_val,0)*px else isnull(abs(D.float_val),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(D.float_val, 0)*px else -isnull(abs(D.float_val), 0)*px end
						end 
				end), Link_Rule, orderCol, coalesce(S.Code, D.Code_Row, '')
	from #t_KS K left join #t_summa S on S.Link_Col = K.Link_Col
		left join #report_dinamics D on D.Link_Col = K.Link_Col and D.Link_Table = K.Link_Table
	where algorithm = 3 and not (S.Code is NULL and D.Code_Row is NULL)
	group by Link_Rule, orderCol, coalesce(S.Code, D.Code_Row, '')
	--having coalesce(S.Code, D.Code_Row, '') <> ''

	update #t_Result_C
	set Value = Value + F
	from (select Link_Rule as LR, sum(case when sign = '+' then Factor else -Factor end) as F from  #t_KS where algorithm = 3 and Val_Type = 1 group by Link_Rule) A
	where Link_Rule = LR

	insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
	select sum(case when sign = '+' then Factor else -Factor end), K.Link_Rule, K.orderCol, coalesce(S.Code, D.Code_Row, '')
	from #t_KS K join #t_KS_Left L on K.Link_Rule = L.Link_Rule
		left join #t_Rows_Static S on S.Link_Table = L.Link_Table
		left join (select distinct Code_Row, Link_Table from #report_dinamics) D on D.Link_Table = L.Link_Table	
	where K.algorithm = 3 and K.Val_Type = 1 and not exists(select top 1 * from #t_Result_C C where C.Link_Rule = K.Link_Rule)
	group by K.Link_Rule, K.orderCol, coalesce(S.Code, D.Code_Row, '')

	delete #t_KS
	where algorithm in (1, 2, 3)	
	-------------------------------------------------------------------------------------------
	-- диапозон строк 

	set @a_count = 0
	exec sp_executesql N'select @count = count(*) from #t_KS where algorithm  = 4', 
                   N'@count int output', @count = @a_count OUTPUT


	while isnull(@a_count,0) > 0 --and (@i < 2)
	begin
		set @i = @i + 1
		select top 1 @LinkRule = Link_Rule,  @ExecStr = 'update #t_Summa set summa = 0
	from #t_Summa S, (select * from #t_KS_Left where Link_Rule = ' + STR(Link_Rule) + ' and Val_Type = 0) K
	where S.Link_Col = K.Link_Col and (' + REPLACE([rows], 'COL(',  '(select case when col_type = 0 then STR((select summa from #t_summa B where B.Link_col = RC.link_col and S.Link_Row = B.Link_Row), 20,4) else (select formula from report_formula F where F.link_col = RC.link_col and F.link_row = S.Link_Row) end from report_coloumns RC where link_table = K.LINK_TABLE and orders =') +  ')
	update #report_dinamics set float_val = 0 from #report_dinamics RD, (select * from #t_KS_Left where Link_Rule = ' + STR(Link_Rule) + ' and Val_Type = 3) K
	where RD.Link_Col = K.Link_Col  and (' + REPLACE(REPLACE([rows],'CODE', 'RD.Code_Row'), 'COL(', '(select top 1 case when RC.Col_Type = 0 then LTRIM(STR(float_val,20,2)) else str_val end from #report_dinamics  RF (nolock) inner join report_coloumns RC on RF.Link_sf = RD.Link_SF and RF.Link_Col = RC.Link_Col   and RF.Code_Row = RD.Code_Row and RC.Link_Table = K.Link_Table and RC.orders =') + ')
	insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
	select  sum(case K.Val_Type 
					when 0 then case [sign] -- статическая таблица
							when ''+'' then case when K.[property] & 2 = 0 then isnull(S.summa,0)*px else isnull(abs(S.summa),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(S.summa ,0)*px else -isnull(abs(S.summa),0)*px end
						end 
					when 1 then  case [sign] -- константа
							when ''+'' then K.Factor
							else -K.Factor
						end 
					else 0
				end), K.Link_Rule, K.orderCol, S.Code
	from (select * from #t_KS where Link_Rule = ' + STR(Link_Rule) + ') K
         inner join #t_summa S on S.Link_Col = K.Link_Col  
	where ' + REPLACE([rows], 'COL(', '(select case when col_type = 0 then STR((select summa from #t_summa B where B.Link_col = RC.link_col and S.Link_Row = B.Link_Row), 20,4) else (select formula from report_formula F where F.link_col = RC.link_col and F.link_row = S.Link_Row) end from report_coloumns RC where link_table = K.LINK_TABLE and orders =') +  '
	group by K.Link_Rule, K.orderCol, S.Code
	having  S.Code <> ''''',
    @ExecStr1 = 'insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
	select sum(case K.Val_Type 
					when 3 then  case [sign] -- динамическая таблица
							when ''+'' then case when K.[property] & 2 = 0 then isnull(RD1.float_val,0)*px else isnull(abs(RD1.float_val),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(RD1.float_val, 0)*px else -isnull(abs(RD1.float_val), 0)*px end
						end 
					when 1 then  case [sign] -- константа
							when ''+'' then K.Factor
							else -K.Factor
						end 
					else 0
				end),  K.Link_Rule, K.orderCol, RD.Code_Row
	from #t_KS K
         inner join #t_KS_LEFT L on K.Link_Rule = L.Link_Rule  
         inner join (select distinct Link_SF, Link_Table, Code_Row from #report_dinamics) RD on K.Link_Table = RD.Link_Table or (K.Val_Type = 1 and RD.Link_Table = L.Link_Table)
         left join #report_dinamics RD1 on RD1.Link_Col = K.Link_Col and K.Link_Table = RD1.Link_Table and RD.Code_Row = RD1.Code_Row  
	where K.Link_Rule = ' + STR(Link_Rule) + ' and (' + REPLACE(REPLACE([rows],'CODE', 'RD.Code_Row'), 'COL(', '(select top 1 case when RC.Col_Type = 0 then LTRIM(STR(float_val,20,2)) else str_val end from #report_dinamics  RF (nolock) inner join report_coloumns RC on RF.Link_sf = RD.Link_SF and RF.Link_Col = RC.Link_Col   and RF.Code_Row = RD.Code_Row and RC.Link_Table = isnull(K.Link_Table,L.Link_Table) and RC.orders =') + ')
	group by K.Link_Rule, K.orderCol, RD.Code_Row
	having RD.Code_Row <> '''''
		from #t_KS
		where algorithm = 4 
		print @ExecStr
		print @ExecStr1
		exec sp_executesql @ExecStr, N'@LSF int', @LSF = @LSF
		exec sp_executesql @ExecStr1, N'@LSF int', @LSF = @LSF
		delete #t_KS where Link_Rule = @LinkRule 
		set @a_count = 0
		exec sp_executesql N'select @count = count(*) from #t_KS where algorithm  = 4', 
					   N'@count int output', @count = @a_count output
	end


	-------------------------------------------------------------------------------------------
	-- хранимки - теперь только одна хранимка в одном правиле!!!
	set @a_count = 0
	exec sp_executesql N'select @count = count(*) from #t_KS where algorithm  = 9 and Val_Type = 2', 
                   N'@count int output', @count = @a_count OUTPUT


	while isnull(@a_count,0) > 0 --and (@i < 2)
	BEGIN
		select top 1 @LinkRule = Link_Rule, @ExecStr = Exec_Proc, @CodeRow = CodeRow
		from #t_KS
		where algorithm = 9 and Val_Type = 2 AND Link_RULE > 0
       
	
	--select @ExecStr
		print @ExecStr
		insert #tmp 
		exec sp_executesql @ExecStr, N'@CodeRow varchar(100)', @CodeRow = @CodeRow

		insert #t_Result_C([Value], Link_Rule, orderCol, CodeRow)
		select (select top 1 Value from #tmp), @LinkRule, 0, @CodeRow
		from #t_KS_Left L
		where Link_Rule = @LinkRule and ((Val_Type = 0 and Link_Col is NOT NULL and Link_Row is NOT NULL) or (Val_Type = 3 and Link_Col is NOT NULL and Code_Row <> ''))
            AND (SELECT COUNT(*) FROM #t_KS K WHERE K.Link_RULE = L.Link_Rule) < 2
             AND CodeRow = @CodeRow 


      UPDATE #t_ks
      SET VALUE = (select top 1 Value from #tmp)
      WHERE @LinkRule = Link_Rule and Val_Type = 2  AND CodeRow = @CodeRow AND [Exec_Proc] = @ExecStr

		delete #tmp
		update #t_KS SET Link_Rule = -Link_Rule where Link_Rule = @LinkRule AND CodeRow = @CodeRow  AND [Exec_Proc] = @ExecStr
		exec sp_executesql N'select @count = count(*) from #t_KS where algorithm  = 9 and Link_Rule > 0 and Val_Type = 2', 
					   N'@count int output', @count = @a_count OUTPUT
	end


	delete #t_KS
	where algorithm = 4

   UPDATE #t_KS
   SET Link_Rule = ABS(Link_RULE)
   
   DELETE #t_KS WHERE [algorithm] = 9 AND (SELECT COUNT(*) FROM #t_KS K WHERE K.Link_RULE = #t_KS.Link_Rule) < 2
   
 

	-------------------------------------------------------------------------------------------
	-- деление и умножение и т.д.
	update #t_KS
   SET VALUE = CASE K.Val_Type
                    WHEN 0 THEN CASE 
                                     WHEN K.[property]&2=0 THEN ISNULL(RS.Summa ,0)
                                         *px
                                     ELSE ISNULL(ABS(RS.Summa) ,0)*px
                                END
                    WHEN 1 THEN K.Factor*px
                    WHEN 3 THEN  CASE 
                                 WHEN K.[property]&2=0 THEN ISNULL(RD.Float_Val ,0)
                                     *px
                                 ELSE ISNULL(ABS(RD.Float_Val) ,0)*px END 
                    ELSE K.[Value]
               END
	from #t_KS K
		left join #t_summa RS on K.link_Col = RS.Link_Col and K.Link_Row = RS.Link_Row
		left join #report_dinamics RD on K.Link_Col = RD.Link_Col and RD.Code_Row = K.Code_Row

	insert @t_temp
	select *
	from #t_KS K
	where CodeRow = '' and exists(select top 1 * from #t_KS K2 where K.Link_Rule = K2.Link_Rule and CodeRow <> '')


	delete #t_KS
	from #t_KS K
	where CodeRow = '' and exists(select top 1 * from #t_KS K2 where K.Link_Rule = K2.Link_Rule and CodeRow <> '')

	-- и для вычисления нужно добавть операнды, которые не размножились
	insert #t_KS
	select K.Link_Rule, K.OrderRow, val_type, [sign], Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], S.orderCol, S.CodeRow, cOrderTable, cOrderCol, px_comment, [property]
	from @t_temp K left join (select distinct Link_Rule, orderCol, CodeRow from #t_KS) S on K.Link_Rule = S.Link_Rule 
	where not exists(select top 1 * from #t_KS S1 where S1.Link_Rule = K.Link_Rule and S1.OrderRow = K.OrderRow and S.CodeRow = S1.CodeRow)

	-- правая часть
	update #t_KS
	set OrderRow = OrderRow - OrRow + 1
	from #t_KS K, (select min(OrderRow) as OrRow, Link_Rule from #t_KS K1 where  part = 1 group by Link_Rule) K2
	where K.Link_Rule = K2.Link_Rule

	insert #t_Result_C ([Value], Link_Rule, orderCol, CodeRow)
	select case [sign] when '+' then Value else -Value end, Link_Rule, orderCol, CodeRow
	from #t_KS K
	where OrderRow = 1

	set @maxOrderRow = isnull((select max(orderRow) from #t_KS ),0)
	set @i = 2
	
	while @i<=@maxOrderRow
	begin

		update R
		set Value = case [sign] when '*' then R.Value * K.Value
								when '/' then case K.Value when 0 then 0 else R.Value / K.Value end
								when '+' then R.Value + K.Value
								when '-' then R.Value - K.Value
					end 
		from #t_Result_C R, #t_KS K
		where K.orderRow = @i and R.Link_Rule = K.Link_Rule and isnull(R.orderCol,0) = isnull(K.orderCol,0) and isnull(R.CodeRow, '') = isnull(K.CodeRow,'') 

		set @i = @i + 1
	end

	-- записываем результат

	update Res
	set Link_Col = K.Link_Col,
		Link_Table = K.Link_Table,
		Value =  round( Res.Value, C.Val_Len) 
	from #t_Result_C Res
         JOIN #t_KS_Left K ON Res.orderCol = 0 and K.Link_Rule = Res.Link_Rule 
         join #t_Col C on K.Link_Col = C.Link_Col

	update Res
	set Link_Col = C.Link_Col,
		Link_Table = K.Link_Table,
		Value = round(CAST(Res.Value AS NUMERIC(22,5)), C.Val_Len) 
	from     #t_KS_Left K 
            join #t_Col C on K.Link_Table = C.Link_Table
            join #t_Result_C Res ON K.Link_Rule = Res.Link_Rule and Res.orderCol = C.orderCol

	update Res
	set Value =  ABS(Res.Value) 
	from     #t_Rules R 
            join #t_Result_C Res ON R.Link_Rule = Res.Link_Rule AND  isnull(IsDoschet, 0) & 16 = 16 


	update #t_Result_C
	set Link_Row = K.Link_Row, CodeRow = R.Code
	from #t_KS_Left K  left join #t_Rows_Static R on K.Link_Row = R.Link_Row
	where isnull(#t_Result_C.CodeRow, '') = '' and K.Val_Type = 0 and K.Link_Rule = #t_Result_C.Link_Rule

	update #t_Result_C
	set Link_Row = R.Link_Row
	from #t_KS_Left K left join #t_Rows_Static R on K.Link_Table = R.Link_Table
	where isnull(#t_Result_C.CodeRow, '') <> '' and K.Val_Type = 0 and K.Link_Rule = #t_Result_C.Link_Rule and R.Code = #t_Result_C.CodeRow

	update #t_Result_C
	set CodeRow = K.Code_Row
	from #t_KS_Left K 
	where isnull(#t_Result_C.CodeRow, '') = '' and K.Val_Type = 3 and K.Link_Rule = #t_Result_C.Link_Rule --and K.orderCol = #t_Result_C.orderCol

	delete #t_Result_C where Link_Col is NULL or (Link_Row is NULL and isnull(CodeRow, '') = '') or Value is NULL
	
	update #report_dinamics
	set float_val = R.Value
	from #t_Result_C R
	where R.Link_Row is NULL and R.Link_Col = #report_dinamics.Link_Col
			and R.CodeRow = #report_dinamics.Code_Row

	insert #report_dinamics(Link_SF, Code_Row, link_col, float_val, str_val, Link_Table)
	select @LSF, R.CodeRow, R.Link_Col, max(R.Value), '', R.Link_Table
	from #t_Result_C R 
	where R.Link_Row is NULL and not exists(select top 1 * from #report_dinamics S where S.Link_Col = R.Link_Col and R.CodeRow = S.Code_Row)
	group by 	R.CodeRow, R.Link_Col, R.Link_Table

	update #t_summa
	set Summa = R.Value
	from #t_Result_C R
	where R.Link_Col = #t_summa.Link_Col and R.Link_Row = #t_summa.Link_Row and R.Link_Row is NOT NULL
	insert #t_summa(LSF, link_col, link_row, Code, summa)
	select @LSF, R.Link_Col, R.Link_Row, max(R.CodeRow), max(R.Value)
	from #t_Result_C R 
	where R.Link_Row is NOT NULL and not exists(select top 1 * from #t_summa S where S.Link_Col = R.Link_Col and S.Link_Row = R.Link_Row)
	group by R.Link_Col, R.Link_Row

	delete @t_temp
	truncate table #t_KS_Left
	truncate table #t_KS
	truncate table #t_Result_C	
end
if @MaxCalcOrders < 100
	exec dbo.RO_Tree_KBK_doschet @LSF
   
   
   
-------------------------------------------------------------------------------
if @cProgressTable <>'' begin
  set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Обновление данных'', percents = 80'
         exec sp_executesql @strProgressExec
 end

update report_summa
set summa = RS.summa
from #t_summa RS join #t_Col on RS.Link_Col = #t_Col.Link_Col
where Link_saved_form = @LSF and RS.Link_Col = report_summa.Link_Col and RS.Link_Row = report_summa.Link_Row

insert report_summa (Link_Saved_form, Link_Col, Link_Row, Summa)
select @LSF, RS.Link_Col, Link_Row, max(Summa)
from #t_summa RS join #t_Col on RS.Link_Col = #t_Col.Link_Col
where not exists(select top 1 * from report_summa RS1 where link_saved_form = @LSF and RS1.Link_Col = RS.Link_Col and RS.Link_Row = RS1.Link_Row)
group by RS.Link_Col, Link_Row
/*
update report_dinamics
set float_val = RD.float_val,
	str_val = RD.str_val
	from report_dinamics D inner join #report_dinamics RD on D.Link_SF = @LSF and RD.Link_Col = D.Link_Col and RD.Code_Row = D.Code_Row
*/

update report_dinamics
set float_val = RD.float_val
from #report_dinamics RD join #t_Col on RD.Link_Col = #t_Col.Link_Col
where report_dinamics.Link_SF = @LSF and RD.Link_Col = report_dinamics.Link_Col and RD.Code_Row = report_dinamics.Code_Row and RD.Float_Val <> report_dinamics.Float_Val


--delete #report_dinamics
--where exists(select top 1 * from report_dinamics RD (NOLOCK) where Link_SF = @LSF and RD.Link_Col = #report_dinamics.Link_Col and RD.Code_Row = #report_dinamics.Code_Row)

delete #report_dinamics
where (isnull(Float_Val,0) = 0 and isnull(Str_Val,'') = '')


----------------------------------------------------------------------------------------------------------
-- колонки, которые можно загрузить из справочника, для динамических таблиц
if @cProgressTable <>'' begin
  set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Загрузка данных из справочника'', percents = 85'
         exec sp_executesql @strProgressExec
 end

declare @table table (orders tinyint)
IF @cTables=''
BEGIN
        insert @table (orders)
        select orders from #report_tables where Val_Type = 1
END
ELSE
BEGIN
        insert @table (orders)
        select orders from #report_tables RT where RT.Val_Type = 1
        and exists(select * from #iTables IT where IT.link_Table=RT.Link_table)
END

while Exists(select * from @table)
begin
  select @orderTable=orders from @table  
  exec dbo.RN_FILL_WITH_DICT @LSF,@LinkF, @orderTable, @cTMP_Table = '#', @varKSiNotUpdate = 1
  delete @table where orders=@orderTable  
end
-------------------------------------------------------------------------------
if @cProgressTable <>'' begin
  set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Добавление данных'', percents = 95'
         exec sp_executesql @strProgressExec
 end

insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
select distinct @LSF, RD.Link_Col, Code_Row, isnull(Float_Val,0), ''
from #report_dinamics RD join #t_Col on RD.Link_Col = #t_Col.Link_Col
where not exists(select top 1 * from report_dinamics RD1 where RD1.Link_SF = @LSF and RD1.Link_Col = RD.Link_Col and RD1.Code_Row = RD.Code_Row)
	and isnull(Str_Val,0) = ''

insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
select distinct @LSF, RD.Link_Col, Code_Row, isnull(Float_Val,0), isnull(Str_Val,'')
from #report_dinamics RD 
where not exists(select top 1 * from report_dinamics RD1 where RD1.Link_SF = @LSF and RD1.Link_Col = RD.Link_Col and RD1.Code_Row = RD.Code_Row)
	and isnull(Str_Val,0) <> ''

--group by Link_Col, Code_Row

-----------------------------------------------------------------------------------------------------------
if @cProgressTable <>'' begin
  set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Завершение расчета итогов'', percents = 95'
         exec sp_executesql @strProgressExec
 end

    exec dbo.RN_SPLIT_CODE_ROW @LSF

drop table #report_coloumns
drop table #t_Col
drop table #t_KS
drop table #t_Row_KS
drop table #t_Rules
drop table #t_Result_C
drop table #t_Rows_Static
drop table #tmp
drop table #report_dinamics
drop table #t_Summa
drop table #report_tables
drop table #t_KS_Left
drop table #t_Rules_region

--GO
--GRANT ALL ON dbo.[RO_CALCULATE_INSIDE1] TO PUBLIC



GO
GRANT ALL ON dbo.[RO_CALCULATE_INSIDE] TO PUBLIC

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	© Кейсистемс (Keysystems), 2006
	Для подсвечивания итоговых ячеек
*/


CREATE PROCEDURE dbo.RO_TOTAL_CELLS
	@iLinkTable int,
	@iLSF	int = NULL,
	@NameCol varchar(8) = 'COL',
	@Mode	tinyint = 0, -- режим: 0 - цвет, 1 - readonly, 2 - цвет и реадонли
	@Code	tinyint = 0,  -- выводить ли поле Code и OrderRow, 0 - не выводить, 1 - выводить
    @cTmpName Varchar(100)='', --требуется для подсчета подитогов 428 формы,
    @tmp_table varchar(200)='', --данные во временную табличку
    @bDeleteEmptyRows BIT = NULL,  --  NULL - данные выбираются не для печати, 1 - удаление пустых строк (поле DEL = 1), 0 - не удалять.
	@web int=0 -- 1 вызов с веба или excel-клиента
as


declare @cStr varchar(8000), 
	@cStr1 varchar(8000),
	@cStr2 varchar(8000),
	@cStr3 varchar(8000),
    @cStr3_1 varchar(8000),
	@cStr4 varchar(8000),
	@cStr5 varchar(8000),
	@cStr0 varchar(8000),
	@ctmp varchar(8000),
	@LinkForm int,
	@LinkCol int,
	@Orders tinyint,
	@ValType tinyint,
	@ColType tinyint,
	@IsEdited tinyint,
	@RGB_zapret varchar(10),
	@RGB_itog varchar(10),
	@RGB_zapret_simple varchar(10),
	@RGB_zapret_itog varchar(10),
	@RGB_name varchar(10),
	@RGB_name_dinamic varchar(10),
	@RGB_simple varchar(10),
    @orders_col int,
	@is_dinamic INT,
   @DictWhere VARCHAR(1000)

IF IS_MEMBER('Свод-КС - ограниченый доступ к организациям') = 1 AND ISNULL((SELECT Val_INT FROM report_options WHERE [Razdel] = 'COMMON' AND CODE = 'ACCESS_WEB'),0) = 0
BEGIN
   SET @web = 1
END       
 
CREATE TABLE #tmp_col (link_col INT)
INSERT #tmp_col (link_col)
select link_col from report_saved_forms_permissions (NOLOCK) where lsf=@iLSF

IF @cTmpName=''
	set @cTmpName='#i_report_dinamic_rows'

set @RGB_zapret = case @Mode when 0 then '14474460' when 2 then '-14474460' else '1' end
set @RGB_itog = case @Mode when 0 then '14483420' when 2 then '14483420' else '0' end
set @RGB_name = case @Mode when 0 then '15790320'  when 2 then '-15790320' else '1' end
set @RGB_simple = case @Mode when 0 then '16777215' when 2 then '16777215' else '0' end
set @RGB_zapret_itog = case @Mode when 0 then '9086343' when 2 then '-9086343'/*'-12189625'*/ else '1' end
set @RGB_zapret_simple = case @Mode when 0 then '12632256' when 2 then '-12632256'/*'-11447982'*/ else '1' end
	
select @is_dinamic=isnull(is_dinamic,0),@LinkForm = Link_Form, @ValType = Val_Type from report_tables where Link_Table = @iLinkTable


if @LinkForm is NULL
	return -1
/*
SELECT *
INTO report_coloumns
FROM dbo.REPORT_COLOUMNS
WHERE link_table = @iLinkTable
*/

DECLARE SEL_CURSOR  CURSOR STATIC LOCAL
	FOR SELECT DISTINCT LINK_Col, Col_Type, IsEdited,orders
	FROM report_coloumns WHERE LINK_Table=@iLinkTable order by orders 

declare @link int,@condrows varchar(2500),@ExecStr nvarchar(4000),@link_col int,@condCols varchar(250),@code_row varchar(100),@link_row int
create table #cols (link_col int)


declare @cDinamic varchar(8000),@cSuffix_table varchar(100)
set @cDinamic=''

declare @sort_kod int
IF exists(select * from report_coloumns where link_col=(select link_code_col from report_tables where link_table=@iLinkTable) and property&8>0)
	set	@sort_kod=1
else
	set	@sort_kod=0
declare @region varchar(250)
--сформируем список доступных правил
create table #tmp_rules_list (LINK_RULE int,REGION varchar(100),orderRule int, Link_Col int, Link_Row int, Code_Row varchar(100), Filter varchar(1000), Val_Type tinyint, IsDoschet tinyint, rows varchar(1000), cols varchar(1000))
Create index #IX_tmp_rules_list on #tmp_rules_list (link_rule,region)
exec X_GET_OPTION 'OBJ_FTP_REGION',0,@cStr output 	
set @region=rtrim(isnull(@cstr,''))
	insert #tmp_rules_list
	SELECT R.[LINK_RULE],
          isnull([REGION],''),OrderRule, Link_Col, Link_Row, Code_Row, Filter, Val_Type, IsDoschet, rows, ',' + REPLACE(REPLACE(cols, ' ',''), '-', '') + ','
	FROM dbo.[REPORT_CONTROL_RULES] [R] (NOLOCK) join dbo.report_control_rows Ro (NOLOCK) on R.Link_Rule = Ro.Link_Rule and Ro.OrderRow = 1 and Ro.Link_Table = @iLinkTable
	 where R.link_form=@LinkForm and IsOutside = 0 and (isnull(R.region,'')=@region or isnull(R.region,'')='')-- and IsDoschet &1 = 1
	IF @region<>''
	begin
		delete #tmp_rules_list 
      from #tmp_rules_list A JOIN dbo.[REPORT_CONTROL_RULES] rcr ON rcr.[LINK_RULE] = A.[LINK_RULE] 
      where A.region='' and 
			exists(select * from report_control_rows C
                              JOIN dbo.[REPORT_CONTROL_RULES] rcr2 ON rcr2.[Link_Rule] = C.[Link_Rule] 
                where C.link_rule in (select link_rule from #tmp_rules_list where region<>'')
                     AND rcr.[sign_sr] = rcr2.[sign_sr]
			            and C.orderRow=1 and isnull(C.link_row,0)=isnull(A.link_row,0) and isnull(C.code_row,'')=isnull(A.code_row,'') and isnull(C.link_col,0)=isnull(A.link_col,0) and isnull(C.link_table,0)=@iLinkTable)

--		delete #tmp_rules_list 
--		WHERE Link_Rule IN (SELECT Ru1.Link_Rule FROM report_control_rules Ru1 JOIN #tmp_rules_list T1 ON Ru1.Link_Rule = T1.Link_Rule 
--						WHERE T1.region='' AND EXISTS(SELECT TOP 1 * FROM report_control_rules Ru2 JOIN #tmp_rules_list T2 ON Ru2.Link_Rule = T2.Link_Rule 
--								WHERE T2.region <> '' AND Ru1.Str_Rule = Ru2.Str_Rule))

	end

delete #tmp_rules_list where IsDoschet & 1 = 0

if @ValType = 0
begin --------------------- таблица статическая ----------------------------------

IF @iLSF>0  and @is_dinamic>0
	begin
		IF exists(select * from report_saved_forms where link_saved_form=@iLSF and is_arhiv=1)
			set @cSuffix_table='_ARH'
		else
			set @cSuffix_table=''
		set @cDinamic=
		' and (exists(select link_row from report_string'+@cSuffix_table+' RS where RS.link_saved_form='+ltrim(str(@iLSF))+' and RS.link_row=RR.link_row)
		or exists(select link_row from report_summa'+@cSuffix_table+' RS where RS.link_saved_form='+ltrim(str(@iLSF))+' and RS.link_row=RR.link_row))'
	end

create table #Stat_filters(link int identity (1,1),filters varchar(2500),link_col int,cols varchar(250),link_row int)
create table #stat_code_row (link_row int,link_col int)

insert #Stat_filters
select CASE WHEN R2.Val_Type=0 AND (R2.LINK_ROW IS NOT NULL OR R2.CODE_ROW <>'') THEN '' ELSE R1.rows END,R2.link_col,R1.cols,R2.link_row
from report_control_rules R1  (nolock) inner join report_control_rows R2 (nolock) on R1.Link_Rule = R2.Link_Rule and R2.OrderRow = 1 and R2.Link_Table = (@iLinkTable)   and IsDoschet&1= 1 and isOutSide=0 and R2.val_type=0 and (R1.rows<>'' or R1.cols<>'' )
	inner join #tmp_rules_list T on T.Link_Rule = R1.Link_Rule
--WHERE R2.Val_Type <> 0  

insert #Stat_filters
select case when R1.rows<>'' then ' (' + CASE WHEN rtrim(R1.rows) LIKE '%#t_summa%' THEN '1=1' ELSE  rtrim(R1.rows) END +') and ' else '' end + R2.filter,R2.link_col,R1.cols,R2.link_row
from report_control_rules R1  (nolock) inner join report_control_rows R2 (nolock) on R1.Link_Rule = R2.Link_Rule and R2.OrderRow = 1 and R2.Link_Table = (@iLinkTable)   and IsDoschet&1 = 1 and isOutSide=0 and R2.val_type=4 and (R2.filter<>'')
	inner join #tmp_rules_list T on T.Link_Rule = R1.Link_Rule

if exists(select * from  #Stat_filters)
    select * into #i_report_rows from i_report_rows A (nolock) where   A.link_table = @iLinkTable

while exists(select top 1 * from  #stat_filters)
begin
  select top 1 @link=link,@CondRows = [filters],@link_col = [link_col],@condCols=[cols],@link_row=link_row from #stat_filters


  delete from #cols
    insert #cols
      select A.Link_Col
      from 
      (select RC.Link_Col, RC.orders
      from report_coloumns RC (nolock)where  RC.Link_Table =@iLinkTable  and RC.Col_Type = 0) A
       where  @link_col = A.link_col OR (@link_col IS NULL AND @condCols = '') or (@condCols <> '' and CHARINDEX(',' + LTRIM(STR(A.Orders)) + ',', ',' + RTRIM(@condCols) + ',') > 0) 
       
       
     IF @CondRows=''
	set @CondRows='1=0'
      set @ExecStr = 'insert #stat_code_row
     select  A.link_row, B.link_col'+
    ' from  #i_report_rows A left join #cols B on B.link_col>0 '+
    ' where A.code<>'''' and  ('+
    REPLACE(CASE WHEN @CondRows LIKE '%#t_summa%' THEN '1=1' ELSE @CondRows END, 'COL(', '(select case when col_type = 0 then STR((select  top 1 summa from report_summa S where Link_Saved_Form = ' + LTRIM(STR(@iLSF))+ ' and S.Link_col = RC.link_col and S.Link_Row = A.Link_Row), 20,4) else (select formula from report_formula F where F.link_col = RC.link_col and F.link_row = A.Link_Row) end from report_coloumns RC where link_table = ' + STR(@iLinkTable) + ' and orders =')
--'dbo.RO_COL_Static(' + LTRIM(STR(@iLinkTable)) + ', A.Link_Row,')
+
    ' or A.link_row='+STR(ISNULL(@link_row,0))+')' 


      execute(@ExecStr)
      delete #stat_filters where link=@link
END


set @cStr1 = '
create table #tmp 
(link_col int,
 link_row int)

Create index #ix_tmp on #tmp (link_row,link_col)

--обработка фильтра правила 
insert #tmp (Link_Col, link_Row)
select  Link_Col, link_Row from #stat_code_row

insert into #tmp (link_col,link_row)
select distinct R2.Link_Col, R2.Link_Row
from report_control_rules R1  (nolock) inner join report_control_rows R2 (nolock) on R1.Link_Rule = R2.Link_Rule and R2.OrderRow = 1 and R2.Link_Table = ' + LTRIM(STR(@iLinkTable)) + ' and IsDoschet&1 = 1 and isOutSide=0 and R2.val_type=0 and (R1.rows='''' and R1.cols='''')
	inner join #tmp_rules_list T on T.Link_Rule = R1.Link_Rule

if exists(select * from #tmp where Link_Col is NULL)
begin
	insert into #tmp (link_col,link_row)
		select RC.Link_Col, T.Link_Row
		from report_coloumns RC left join #tmp T on T.Link_Col is NULL
		where Link_table = ' + LTRIM(STR(@iLinkTable)) + ' and RC.IsEdited=1 and RC.Col_Type=0
	delete from #tmp where Link_Col is null
end
if exists(select * from #tmp where Link_Row is NULL)
begin
	insert into #tmp (link_col,link_row)
		select T.Link_Col, RR.Link_Row
		from report_rows RR (nolock) left join #tmp T on T.Link_Row is NULL 
		where Link_table = ' + LTRIM(STR(@iLinkTable)) + '
	delete #tmp where Link_Row is null
end'

set @cStr = '
select ' + case @Code when 1 then 'convert(varchar(100), isnull(Code,'''')) as Cod, Orders as OrderRow, ' else '' end
set @cStr2 = ''
set @cStr3 = ''
set @cStr3_1 = ''
set @cStr4 = ''
set @cStr5 = ''

--set @Orders = 1 -- считается не по порядковому номеру столбца, т.к. он может быть не по порядку
OPEN SEL_CURSOR
FETCH NEXT FROM SEL_CURSOR INTO @LinkCol, @ColType, @IsEdited,@orders_col
set @Orders =@orders_col
while @@fetch_status = 0
begin

	IF @cDinamic<>'' and @IsEdited=0 
		set @RGB_name = case @Mode when 0 then '15790320'  when 2 then '16777215' else '1' end
	else
		set @RGB_name = case @Mode when 0 then '15790320'  when 2 then '-15790320' else '1' end


	if @Orders < 15 
	begin
	if @IsEdited = 1 and dbo.RO_AccessColByLink(@LinkCol) > 0 
            and (not exists(select * from #tmp_col where link_col=@LinkCol) or @web<>1 )
	begin
	set @cStr = @cStr + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row=RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row=RR.Link_Row and Link_Col=' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_itog + ' else ' + @RGB_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
	end
	else
		if @IsEdited = 0 -- наименования, код строки
		begin
			set @cStr = @cStr + '
' + @RGB_Name + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
		end
		else begin -- нет доступа к колонке
--			set @cStr = @cStr + '
--' + @RGB_Zapret + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
	set @cStr = @cStr + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row=RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row=RR.Link_Row and Link_Col=' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_zapret_itog + ' else ' + @RGB_zapret_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '

		end
	end
	else begin
	if @Orders < 27
	begin
		if @IsEdited = 1 and dbo.RO_AccessColByLink(@LinkCol) > 0
            and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
		begin
		set @cStr2 = @cStr2 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row=RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row=RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row=RR.Link_Row and Link_Col=' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_itog + ' else ' + @RGB_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
		end
		else begin
			if @IsEdited = 0 -- наименования, код строки
			begin
				set @cStr2 = @cStr2 + '
' + @RGB_Name + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			end
			else begin -- нет доступа к колонке
--				set @cStr2 = @cStr2 + '
--' + @RGB_Zapret + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
		set @cStr2 = @cStr2 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row=RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col=' + LTRIM(STR(@LinkCol)) + ' and Link_Row=RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row=RR.Link_Row and Link_Col=' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_zapret_itog + ' else ' + @RGB_zapret_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '

			end
		end
	end
	else begin
		if @Orders < 38
		begin
			if @IsEdited = 1 and dbo.RO_AccessColByLink(@LinkCol) > 0
               and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
			begin
			set @cStr3 = @cStr3 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF  (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row = RR.Link_Row and Link_Col = ' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_itog + ' else ' + @RGB_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			end
			else begin
				if @IsEdited = 0 -- наименования, код строки
				begin
					set @cStr3 = @cStr3 + '
' + @RGB_Name + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
				end
				else begin -- нет доступа к колонке
--					set @cStr3 = @cStr3 + '
--' + @RGB_Zapret + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			set @cStr3 = @cStr3 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF  (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row = RR.Link_Row and Link_Col = ' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_zapret_itog + ' else ' + @RGB_zapret_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '

				end
			end
		end
	else begin
		if @Orders < 48
		begin
			if @IsEdited = 1 and dbo.RO_AccessColByLink(@LinkCol) > 0
                and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
			begin
			set @cStr3_1 = @cStr3_1 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF  (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row = RR.Link_Row and Link_Col = ' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_itog + ' else ' + @RGB_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			end
			else begin
				if @IsEdited = 0 -- наименования, код строки
				begin
					set @cStr3_1 = @cStr3_1 + '
' + @RGB_Name + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
				end
				else begin -- нет доступа к колонке
--					set @cStr3_1 = @cStr3_1 + '
--' + @RGB_Zapret + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			set @cStr3_1 = @cStr3_1 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF  (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row = RR.Link_Row and Link_Col = ' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_zapret_itog + ' else ' + @RGB_zapret_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '

				end
			end
		end
		else begin
			if @IsEdited = 1 and dbo.RO_AccessColByLink(@LinkCol) > 0 
               and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
			begin
			set @cStr4 = @cStr4 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row = RR.Link_Row and Link_Col = ' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_itog + ' else ' + @RGB_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			end
			else begin
				if @IsEdited = 0 -- наименования, код строки
				begin
					set @cStr4 = @cStr4 + '
' + @RGB_Name + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
				end
				else begin -- нет доступа к колонке
--					set @cStr4 = @cStr4 + '
--' + @RGB_Zapret + ' as [' + @NameCol + LTRIM(STR(@Orders)) + '], '
			set @cStr4 = @cStr4 + '
case when PATINDEX(''%ЗАПРЕТ%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0 then ' + @RGB_zapret + ' when PATINDEX(''%ИТОГ%'',isnull((select top 1 formula from report_formula RF where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or PATINDEX(''%ГР%'',isnull((select top 1 formula from report_formula RF (nolock) where RF.Link_Col = ' + LTRIM(STR(@LinkCol)) + ' and Link_Row = RR.Link_Row),''''))>0
or exists(select * from #tmp T where T.Link_Row = RR.Link_Row and Link_Col = ' + LTRIM(STR(@LinkCol)) + ')
then ' + @RGB_zapret_itog + ' else ' + @RGB_zapret_simple + ' end as [' + @NameCol + LTRIM(STR(@Orders)) + '], '

				end
			end
		end
	end
	END
   END
	FETCH NEXT FROM SEL_CURSOR INTO @LinkCol, @ColType, @IsEdited,@orders_col
	set @Orders =@orders_col
--	set @Orders = @Orders + 1
end
if @cStr2 = ''
begin
	set @cStr = LEFT(RTRIM(@cStr),LEN(RTRIM(@cStr)) - 1)
--	set @cStr = @cStr + '
--	'+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' from i_report_rows RR (nolock) where Link_Table=' + LTRIM(STR(@iLinkTable)) + @cDinamic+' order by RR.orders'
end
else begin
	if @cStr3 = ''
	begin
		set @cStr2 = LEFT(RTRIM(@cStr2),LEN(RTRIM(@cStr2)) - 1)
--		set @cStr2 = @cStr2 + '
--     '+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
 --order by RR.orders'
	end
	else begin
	   if @cStr3_1 = ''
	   begin
		   set @cStr3 = LEFT(RTRIM(@cStr3),LEN(RTRIM(@cStr3)) - 1)
   --		set @cStr2 = @cStr2 + '
   --     '+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
    --order by RR.orders'
	   end
	   else begin
		   if @cStr4 = ''
		   begin
			   set @cStr3_1 = LEFT(RTRIM(@cStr3_1),LEN(RTRIM(@cStr3_1)) - 1)
   --			set @cStr3 = @cStr3 + '
   --	'+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
   --	 from i_report_rows RR where Link_Table=' + LTRIM(STR(@iLinkTable)) + ' order by RR.orders'
		   end
		   else begin
			   set @cStr4 = LEFT(RTRIM(@cStr4),LEN(RTRIM(@cStr4)) - 1)
   --			set @cStr4 = @cStr4 + '
   --	'+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
   --	 from i_report_rows RR where Link_Table=' + LTRIM(STR(@iLinkTable)) + ' order by RR.orders'
         end
		end
	end
end

	set @cStr5 = @cStr5 + '
	'+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
	 from i_report_rows RR where Link_Table=' + LTRIM(STR(@iLinkTable)) +@cDinamic+ ' order by RR.'+case when @sort_kod=1 then 'CODE' else 'orders' end




execute(@cStr1 + @cStr + @cStr2 + @cStr3 + @cStr3_1 + @cStr4+@cStr5  /* +' drop table #tmp'*/)

end------------------------------------------------------------------------
else begin ------------------------- таблица динамическая -----------------
if @iLSF is NULL
	return -2
----------------------------------------------------------------------------
-- новая подкраска:
	declare @IsArchive tinyint, @WithCol tinyint
	create table #Cells (Link_Col int, Code_Row varchar(100))
	create table #t_Exec (txt varchar(8000))
	create table #Coloumns (Link_Col int, orders tinyint, Col_Type tinyint)

	insert #Coloumns (Link_Col, orders, Col_Type)
	select Link_Col, orders, Col_Type
	from dbo.report_coloumns 
	where Link_Table = @iLinkTable --and Col_Type = 0

	if exists(select top 1 * from #tmp_rules_list where rows like '%COLS(%' or filter like '%COLS(%' or rows like '%COL(%' or filter like '%COL(%' or rows like '%report_dinamic%' or filter like '%report_dinamic%')
		set @WithCol = 1
	else
		set @WithCol = 0
	
	--create table #tmp_rules_list1 (LINK_RULE int,REGION varchar(100),orderRule int, Link_Col int, Link_Row int, Code_Row varchar(100), Filter varchar(1000), Val_Type tinyint, IsDoschet tinyint, rows varchar(1000), cols varchar(1000))

--	select @IsArchive = Is_Arhiv from dbo.report_saved_forms where Link_Saved_Form =@iLSF 

		create table #i_report_dinamic_rows(Link_SF int,CODE_ROW varchar(100),link_table INT, link_col INT, float_val FLOAT, str_val VARCHAR(8000), for_rash char(3), for_doh char(10))

	Create index #IX_report_dinamics on #i_report_dinamic_rows (link_col,code_row)
	Create index #IX_report_dinamics_rash on #i_report_dinamic_rows (link_sf, link_col,for_rash)
	Create index #IX_report_dinamics_doh on #i_report_dinamic_rows (link_sf, link_col,for_doh)

--	while exists(select top 1 * from #Coloumns)
--	begin
--		select top 1 @link = link_col from 	#Coloumns	
--		set @ExecStr='INSERT #i_report_dinamic_rows (Link_SF,CODE_ROW,link_table,link_col,float_val, str_val, for_rash) SELECT 	' + str(@iLSF) + ', 	RD.Code_Row, 	' + LTRIM(STR(@iLinkTable)) + ', RD.Link_Col, RD.Float_Val, RD.Str_Val, RIGHT(RTRIM(RD.Code_Row),3)
--			FROM '+CASE WHEN @cTmpName = '#i_report_dinamic_rows' THEN case when  @IsArchive = 0 then 'dbo.report_dinamics' else 'dbo.report_dinamics_arh' end ELSE @cTmpName END +' RD where  RD.link_col = ' + STR(@link) + ' and RD.Link_SF ='+str(@iLSF)
--		execute(@ExecStr)
--		delete #Coloumns where link_col = @link
--	end

	if @cTmpName = '#i_report_dinamic_rows'
	begin
		if @WithCol = 1
		begin
			while exists(select top 1 * from #Coloumns)
			begin
				select top 1 @link = link_col from 	#Coloumns	
				INSERT #i_report_dinamic_rows (Link_SF,CODE_ROW,link_table,link_col,float_val, str_val, for_rash, for_doh) SELECT 	@iLSF,	RD.Code_Row, 	@iLinkTable, RD.Link_Col, RD.Float_Val, RD.Str_Val, RIGHT(RTRIM(RD.Code_Row),3), left(RD.code_row,10)
					FROM dbo.report_dinamics_all RD where  RD.link_col = @link and RD.Link_SF =@iLSF
				delete #Coloumns where link_col = @link
			end
		end
		else begin
			INSERT #i_report_dinamic_rows (Link_SF,CODE_ROW,link_table,link_col,float_val, str_val, for_rash, for_doh) 
			SELECT 	@iLSF, 	RD.Code_Row, 	@iLinkTable, 0, 0, '', RIGHT(RTRIM(RD.Code_Row),3), left(RD.code_row,10)
			FROM dbo.report_dinamics_all  RD join dbo.report_coloumns RC on RD.link_col = RC.Link_Col and RD.Link_SF = @iLSF and RC.link_table = @iLinkTable
			group by RD.Code_Row
		end
	end
	else begin
		set @ExecStr='INSERT #i_report_dinamic_rows (Link_SF,CODE_ROW,link_table,link_col,float_val, str_val, for_rash, for_doh) SELECT 	' + str(@iLSF) + ', 	RD.Code_Row, 	RC.link_table, RD.Link_Col, RD.Float_Val, RD.Str_Val, RIGHT(RTRIM(RD.Code_Row),3), left(RD.Code_Row,10)
			FROM '+ @cTmpName +' RD left join report_coloumns RC
			on RD.link_col = RC.Link_Col and RC.link_table = '+str(@iLinkTable)
		execute(@ExecStr)
	end

	-- когда указаны строки:
	insert #Cells (Link_Col, Code_Row)
	select RC.Link_Col, Code_Row
	from #tmp_rules_list T left join dbo.report_coloumns RC on RC.Link_Table = @iLinkTable and RC.Col_Type = 0 and (RC.Link_Col = T.Link_Col or T.Link_Col is NULL)
	where Val_Type = 3 and  isnull(Code_Row, '') <> '' and (T.cols = ',,' or CHARINDEX(',' + LTRIM(RTRIM(STR(RC.orders))) + ',', T.cols) > 0)

	delete #tmp_rules_list where Val_Type = 3 and isnull(Code_Row, '') <> ''
	-- для всех строк
	insert #Cells (Link_Col, Code_Row)
	select RC.Link_Col, D.Code_Row
	from #tmp_rules_list T left join dbo.report_coloumns RC on RC.Link_Table = @iLinkTable and RC.Col_Type = 0 and (RC.Link_Col = T.Link_Col or T.Link_Col is NULL)
			left join #i_report_dinamic_rows D on 1 = 1
	where Val_Type = 3 and T.rows = '' and  isnull(T.Code_Row, '') = ''  and (T.cols = ',,' or CHARINDEX(',' + LTRIM(RTRIM(STR(RC.orders))) + ',', T.cols) > 0)

	delete #tmp_rules_list where Val_Type = 3 and rows = ''

	-- не указаны строки:
		update #tmp_rules_list
		set filter = REPLACE(REPLACE(REPLACE(filter, 'right(rtrim(code),3)', 'A.for_rash'), 'left(code,10)', 'A.for_doh'), 'left(RD1.Code_row,10)', 'RD1.for_doh')
		update #tmp_rules_list
		set filter = REPLACE(filter, 'right(rtrim(RD1.code_row),3)', 'RD1.for_rash')

		while exists(select top 1 * from  #tmp_rules_list where Val_Type = 4 or rows <> '')
		begin
--		insert #t_Exec (txt)
		  select @link = Link_Rule, @ExecStr = --'insert #tmp_rules_list1 (LINK_RULE,REGION,orderRule, Link_Col, Link_Row, Code_Row, Filter, Val_Type, IsDoschet, rows, cols) ' + 
			'insert #Cells (Link_Col, Code_Row)' +
		 --'select ' + LTRIM(RTRIM(STR(Link_Rule))) + ', '''', 0, ' + isnull(STR(Link_Col), 'NULL') + ' , NULL, A.Code_Row, '''', 3, 1, '''', '''+ cols + ''' '  +
		'select B.Link_Col, A.Code_Row from  #i_report_dinamic_rows A left join dbo.report_coloumns B on B.Link_Table = ' + LTRIM(STR(@iLinkTable)) + ' and B.col_type = 0 '+ case when Link_Col is NOT NULL then ' and B.Link_Col = ' + LTRIM(STR(Link_Col)) else '' end +
		' where ' + case when cols <> ',,' and Link_Col is NULL then 'CHARINDEX('','' + LTRIM(RTRIM(STR(B.orders))) + '','', ''' + cols +  ''') > 0 and ' else '' end +	REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE((case when [filter] <> '' then '(' + RTRIM(filter) + ')' else '(1=1)' end + case when [rows] <> '' then ' and (' + RTRIM([rows]) + ')' else '' end ),'report_dinamics_all','#i_report_dinamic_rows'), 'report_dinamics', '#i_report_dinamic_rows'), 'CODE', 'A.Code_Row'),'.A.Code_Row', '.CODE'), 'COL(','(select top 1 case when Col_Type = 0 then float_val else str_val end from '+@cTmpName+'  RF (nolock) inner join report_coloumns RC (nolock) on RF.Link_sf = ' + LTRIM(STR(@iLSF))+' and RF.Link_Col = RC.Link_Col   and RF.Code_Row = A.Code_Row and RC.Link_Table =' + LTRIM(STR(@iLinkTable))+' and RC.orders ='), '##i_report_dinamic_rows', '#i_report_dinamic_rows'), 'COLS(','(select top 1 str_val from '+@cTmpName+'  RF (nolock) inner join report_coloumns RC (nolock) on RF.Link_sf = ' + LTRIM(STR(@iLSF))+' and RF.Link_Col = RC.Link_Col   and RF.Code_Row = A.Code_Row and RC.Link_Table =' + LTRIM(STR(@iLinkTable))+' and RC.orders =')
		from #tmp_rules_list T where Val_Type = 4 or rows <> ''
		

  	-- атрибуты в фильтрах
   SELECT @ExecStr = REPLACE(@ExecStr, '#' + rtrim(code_atr) + '#', '''' + str_val + '''')
   FROM dbo.[REPORT_ATRIBUT_VALUES] rav
   WHERE rav.[link_saved_form] = @ilsf
   
   SELECT  @ExecStr = REPLACE(@ExecStr, '#' + rtrim(SO1.code) + '#', '''' + isnull(OV.[VALUE],'') + '''')
   FROM dbo.s_objects SO
         JOIN dbo.s_objects SO1 ON SO.[LINK] = SO1.[LINK_SELF]
         JOIN dbo.s_property P ON P.Code = 'DEFAULT_VALUE'
         JOIN dbo.[OBJECT_VALUES] ov ON ov.[OBJECT] = SO1.[LINK] AND ov.[PROPERTY] = P.[LINK] 
   WHERE SO.Code = 'REPORTS_ATR'
              

--			exec ssp_execresultset 'select txt from #t_Exec'--, @varKSDebug = 1
		print @ExecStr
      PRINT @link
			exec sp_executesql @ExecStr, N'@link_rule int', @link_rule = @link
--
			delete #tmp_rules_list where link_rule=@link
		end

	-- по ДЕРЕВУ КБК досчет
   CREATE table #t_TreeKBK_cols (Link_Table int, Cols varchar(100))

	insert #t_TreeKBK_cols (Link_Table, Cols)
	select Link_Table, replace(isnull(dbo.rn_get_formula_code_row_f(Link_Table,'KBK='),''),'-', '')
	from report_tables rt
   WHERE link_table = @iLinkTable
         
   UPDATE #t_TreeKBK_cols
   SET cols = ''
   WHERE cols LIKE '%(%' AND (cols NOT LIKE '%' + RTRIM(@region) + '%' OR @region = '') 
   
	declare @Dict varchar(100)
	select @Dict = Dictionary, @DictWhere = isnull(RC.[Dictionary_Where],'')
	  from report_tables RT join report_coloumns RC on RT.Link_Code_Col = RC.Link_Col where Doschet_Tree = 1 and isnull(Dictionary,'') <> '' and RT.Link_Table = @iLinkTable
	if isnull(@Dict, '') <> ''
	begin
		if COLUMNPROPERTY(object_id('[dbo].' + LTRIM(RTRIM(@Dict))), 'Link_Self', 'AllowsNull') is NOT NULL
		BEGIN
            SELECT @DictWhere = REPLACE(REPLACE(REPLACE(@DictWhere, '%link_org%', LTRIM(STR(rsf.[Link_Organization]))), '%link_budg%', LTRIM(STR(ISNULL(rsf.[Link_Type_Svod], 0)))), '%date%', '''' + CONVERT(VARCHAR(10), rsf.[Begin_Date], 112) + '''')
            FROM dbo.[REPORT_SAVED_FORMS] rsf
            WHERE rsf.[Link_Saved_Form] = @iLSF
            
            IF ISNULL(@iLSF, 0) = 0
            BEGIN
               IF (SELECT code FROM dbo.[REPORT_FORMS] rf WHERE rf.[Link_Form] = @LinkForm) LIKE '%G%'
                  SET @DictWhere = REPLACE(REPLACE(REPLACE(@DictWhere, '%link_org%', '0'), '%link_budg%', '0'), '%date%', '''' + CONVERT(VARCHAR(10), DATEADD(MONTH,-3, GETDATE()), 112) + '''')
               ELSE                   
                  SET @DictWhere = REPLACE(REPLACE(REPLACE(@DictWhere, '%link_org%', '0'), '%link_budg%', '0'), '%date%', '''' + CONVERT(VARCHAR(10), DATEADD(MONTH,-1, GETDATE()+10), 112) + '''')
            END    
         
			  set @ExecStr = 'insert #Cells
				select  B.Link_Col, T.Code
				from dbo.' + RTRIM(@Dict) + ' T join dbo.report_coloumns B on B.Link_Table = @iLinkTable and B.Col_Type = 0
               join #t_TreeKBK_cols tc on tc.link_table = B.link_table AND (CHARINDEX('','' + LTRIM(RTRIM(STR(B.orders))) + '','', '','' + rtrim(tc.cols) + '','') > 0 OR cols = '''')
				where  exists(select * from dbo.' + LTRIM(@Dict) + ' T1 where T1.Link_Self = T.Link ' + CASE WHEN @DictWhere = '' THEN  '' ELSE ' and ' + @DictWhere END  + ' ) '
				--print @ExecStr
				exec sp_executesql @ExecStr, N'@iLinkTable int', @iLinkTable = @iLinkTable
		end
	end

--	insert #t_Exec (txt)
	select @cStr = case when @Code = 0 then 'select ' else 'select RD.Code_Row as Cod,0 as OrderRow,' end

OPEN SEL_CURSOR
FETCH NEXT FROM SEL_CURSOR INTO @LinkCol, @ColType, @IsEdited,@orders_col
--set @Orders = 1
set @Orders =@orders_col
while @@fetch_status = 0
begin
	if dbo.RO_AccessColByLink(@LinkCol) > 0 
         and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
	begin
		set @cStr = @cStr + @NameCol + LTRIM(STR(@Orders)) + '=min(case when T.Link_Col=' + LTRIM(STR(@LinkCol)) + ' then ' + @RGB_itog + ' else '+@RGB_simple+' end),
'
		end
		else begin -- нет доступа к колонке
--			set @cStr = @cStr + @NameCol + LTRIM(STR(@Orders)) + '=' + @RGB_zapret + ',
--'		
		set @cStr = @cStr + @NameCol + LTRIM(STR(@Orders)) + '=' + CASE WHEN @Mode = 2 THEN 'max' ELSE  'min' END + '(case when T.Link_Col=' + LTRIM(STR(@LinkCol)) + ' then ' + @RGB_zapret_itog + ' else '+@RGB_zapret_simple+' end),
'

      end
	FETCH NEXT FROM SEL_CURSOR INTO @LinkCol, @ColType, @IsEdited,@orders_col
	set @Orders =@orders_col
end
set @cStr = LEFT(@cStr, LEN(@cStr) - 3)

-----------------------------------------------------------
-- сортировка
   DECLARE @order_rule VARCHAR(8000), @order_rule_new VARCHAR(8000), @count_rule INT, @i INT, @order_rule_curr VARCHAR(8000)
	select @order_rule=rtrim(isnull(order_rule,'')) from report_tables where link_table = @iLINKTABLE
	set @order_rule_new=''
	--превратим @order_rule в условие
	IF @order_rule<>''
		begin
			set @order_rule_new=' case '
			set @count_rule=dbo.rn_getwordcount(@order_rule,char(13))
			set @i=1
			while @i<=@count_rule
				begin
					set @count_rule=dbo.rn_getwordcount(@order_rule,char(13))
					set @order_rule_curr=rtrim(dbo.rn_getwordnum(@order_rule,@i,char(13)))
					IF  @order_rule_curr<>''
						set @order_rule_new=@order_rule_new +' when '+ replace(UPPER(dbo.rn_getwordnum(@order_rule_curr,2,'#')),'CODE','RD.CODE_ROW')+' then '+REPLACE(dbo.rn_getwordnum(@order_rule_curr,1,'#'), 'RR.CODE_ROW', 'RD.CODE_ROW')
					set @i=@i+1
				end
			set @order_rule_new=@order_rule_new+' else 0 end ' 
		end
-----------------------------------------------------------

if @WithCol = 1
	set @cStr2 = case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
	from (SELECT DISTINCT code_row from #i_report_dinamic_rows) RD left join
		#Cells T on RD.Code_Row = T.Code_Row 
	group by RD.Code_Row
	order by ' + case when @order_rule_new <> '' then @order_rule_new + ',' ELSE '' end + ' RD.Code_Row'

else
	set @cStr2 = case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
	from   #i_report_dinamic_rows RD left join
		#Cells T on RD.Code_Row = T.Code_Row 
	group by RD.Code_Row
	order by ' + case when @order_rule_new <> '' then @order_rule_new + ',' ELSE '' end + ' RD.Code_Row'

--
CLOSE SEL_CURSOR
DEALLOCATE SEL_CURSOR

--set  @cStr = 'select count(*) '

--PRINT @cStr + @cStr2
execute (@cStr + @cStr2)	
return
------------------------------------------------------
--- старая подкраска:
--declare @name_table varchar(100)
--create table #filters_d (link int identity (1,1),filters varchar(2500),link_col int,cols varchar(250),code_row varchar(100))
--create table #code_row (code_row varchar(100),link_col int)
----create table #i_report_dinamic_rows(Link_SF int,CODE_ROW varchar(100),link_table INT, link_col INT, float_val FLOAT, str_val VARCHAR(8000), for_rash char(3))
--
--Create index #IX_report_dinamics on #i_report_dinamic_rows (link_sf, link_col,code_row)
--Create index #IX_report_dinamics_rash on #i_report_dinamic_rows (link_sf, link_col,for_rash)
--
--insert #filters_d
--select R1.rows,R2.link_col,R1.cols,R2.code_row
--from report_control_rules R1 (nolock) inner join report_control_rows R2 (nolock) on R1.Link_Rule = R2.Link_Rule and R2.OrderRow = 1 and R2.Link_Table = (@iLinkTable)   and IsDoschet&1 = 1 and isOutSide=0 and R2.val_type=3 and (R1.rows<>'' or R1.cols<>'' )
--where exists(select link_rule from #tmp_rules_list A where A.link_rule=R1.link_rule)
--
--
--insert #filters_d
--select R2.filter + case when R1.rows = '' then '' else ' and (' + R1.rows + ')' end ,R2.link_col,R1.cols,R2.code_row
--from report_control_rules R1 (nolock) inner join report_control_rows R2 (nolock) on R1.Link_Rule = R2.Link_Rule and R2.OrderRow = 1 and R2.Link_Table = (@iLinkTable)   and IsDoschet&1 = 1 and isOutSide=0 and R2.val_type=4 and (R2.filter<>'')--(R1.rows<>'' or R1.cols<>'' )
--where exists(select link_rule from #tmp_rules_list A where A.link_rule=R1.link_rule) 
--
----if exists(select * from  #filters_d)
----	begin
--		set @ExecStr='INSERT #i_report_dinamic_rows (Link_SF,CODE_ROW,link_table,link_col,float_val, str_val, for_rash) SELECT 	' + str(@iLSF) + ', 	RD.Code_Row, 	RC.link_table, RD.Link_Col, RD.Float_Val, RD.Str_Val, RIGHT(RTRIM(RD.Code_Row),3)
--			FROM '+CASE WHEN @cTmpName = '#i_report_dinamic_rows' THEN 'report_dinamics_all' ELSE @cTmpName END +' RD left join report_coloumns RC
--			on RD.link_col = RC.Link_Col
--			where  RD.Link_SF ='+str(@iLSF)+'  and RC.link_table = '+str(@iLinkTable)
--		execute(@ExecStr)
--
--set @name_table = case when @iLSF = 0 then 'report_dinamics_all' else '#i_report_dinamic_rows' end
----	end
--
----select * into ##i_report_dinamic_rows from #i_report_dinamic_rows
----
----  select A.Link_Col
----into ##cols
----  from 
----      (select RC.Link_Col, RC.orders
----      from report_coloumns RC (nolock)where  RC.Link_Table =@iLinkTable  and RC.Col_Type = 0) A
--
--if @iLSF > 0
--begin
--	update #filters_d
--	set filters = REPLACE(filters, 'right(rtrim(code),3)', 'A.for_rash')
--	update #filters_d
--	set filters = REPLACE(filters, 'right(rtrim(RD1.code_row),3)', 'RD1.for_rash')
--end
--
--
--while exists(select top 1 * from  #filters_d)
--begin
--
--  select top 1 @link=link,@CondRows = [filters],@link_col = [link_col],@condCols=[cols],@code_row=code_row from #filters_d
--
--delete from #cols
--insert #cols
--  select A.Link_Col
--  from 
--      (select RC.Link_Col, RC.orders
--      from report_coloumns RC (nolock)where  RC.Link_Table =@iLinkTable  and RC.Col_Type = 0) A
--       where  @link_col = A.link_col OR (@link_col IS NULL AND @condCols = '') or (@condCols <> '' and CHARINDEX(',' + LTRIM(STR(A.Orders)) + ',', ',' + RTRIM(@condCols) + ',') > 0) 
-- 
--  IF @CondRows=''
--	set @CondRows='1=0'
--  set @ExecStr = 'insert #code_row
-- select  A.Code_Row, B.link_col'+
--' from  #i_report_dinamic_rows A left join #cols B on B.link_col = A.Link_Col OR B.Link_Col > 0 '+
--' where A.code_row<>'''' and  ('+
--REPLACE(REPLACE(REPLACE(REPLACE(@CondRows,'report_dinamics_all',@name_table), 'CODE', 'A.Code_Row'),'.A.Code_Row', '.CODE'), 'COL(','(select top 1 case when Col_Type = 0 then float_val else str_val end from '+@cTmpName+'  RF (nolock) inner join report_coloumns RC (nolock) on RF.Link_sf = ' + LTRIM(STR(@iLSF))+' and RF.Link_Col = RC.Link_Col   and RF.Code_Row = A.Code_Row and RC.Link_Table =' + LTRIM(STR(@iLinkTable))+' and RC.orders =')+'
--or A.code_row='''+RTRIM(@code_row)+''')' 
--
--  exec sp_executesql @ExecStr
--
--  delete #filters_d where link=@link
--
--
--end
--
---- по ДЕРЕВУ КБК досчет
----declare @Dict varchar(100)
--select @Dict = Dictionary from report_tables RT join report_coloumns RC on RT.Link_Code_Col = RC.Link_Col where Doschet_Tree = 1 and isnull(Dictionary,'') <> '' and RT.Link_Table = @iLinkTable
--if isnull(@Dict, '') <> ''
--begin
--	if COLUMNPROPERTY(object_id('[dbo].' + LTRIM(RTRIM(@Dict))), 'Link_Self', 'AllowsNull') is NOT NULL
--	begin
--		delete #cols
--		insert #cols
--		select RC.Link_Col
--		from report_coloumns RC (nolock)where  RC.Link_Table =@iLinkTable  and RC.Col_Type = 0
--
--		  set @ExecStr = 'insert #code_row
--			select T.Code, B.Link_Col
--			from dbo.' + RTRIM(@Dict) + ' T , #cols B 
--			where  exists(select * from dbo.' + LTRIM(@Dict) + ' T1 where T1.Link_Self = T.Link) '
--			--print @ExecStr
--			execute(@ExecStr)
--	end
--end
--
--------------------
--set @cStr1 = 'declare @tmp table (Link_Col int, CodeRow varchar(100))
--insert @tmp (Link_Col, CodeRow)
--select distinct Link_Col, Code_Row as CodeRow
--from report_control_rules R1  inner join report_control_rows R2 (nolock) on R1.Link_Rule = R2.Link_Rule and R2.OrderRow = 1 and R2.Link_Table = ' + LTRIM(STR(@iLinkTable)) + ' and IsDoschet&1 = 1 and isOutSide=0 and R2.val_type=3 and (R1.rows='''' and	 R1.cols='''')
--where exists(select link_rule from #tmp_rules_list A where A.link_rule=R1.link_rule)
--
----обработка фильтра правила 
--insert @tmp (Link_Col, CodeRow)
--select  Link_Col, Code_Row from #code_row
--
--insert @tmp (Link_Col, CodeRow)
--select RC.Link_Col, Code_Row as CodeRow
--from report_dinamic_totals RDT left join report_coloumns RC (nolock) on RDT.Link_Table = RC.Link_Table and RC.orders = RDT.Order_Col
--where RDT.Link_Table = ' + LTRIM(STR(@iLinkTable)) + '
--
--if exists(select top 1 * from @tmp where Link_Col is NULL)
--begin
--	insert into @tmp
--		select RC.Link_Col, T.CodeRow
--		from report_coloumns RC left join @tmp T on T.Link_Col is NULL
--		where Link_table = ' + LTRIM(STR(@iLinkTable)) + ' and RC.IsEdited = 1 and RC.Col_Type = 0
--	delete @tmp where Link_Col is NULL
--end
--
--declare @Code table (Cod varchar(100) not null, LT int)
--insert @Code (Cod, LT) 
--
--select distinct Code_Row as Code, RC.Link_Table from '+ @cTmpName+' RD left join report_coloumns RC on RD.Link_Col = RC.Link_Col where RD.Link_SF =' + LTRIM(STR(@iLSF)) + ' and RC.Link_Table = ' + LTRIM(STR(@iLinkTable)) + 
--case when @bDeleteEmptyRows=1 then ' and abs(RD.float_val) > 0.001' else '' end +'
--if exists(select top 1 * from @tmp where LTRIM(ISNULL(CodeRow,'''')) = '''')
--begin
--	insert @tmp
--		select T.Link_Col, RR.Cod
--		from @Code RR left join @tmp T on LTRIM(ISNULL(T.CodeRow,'''')) = ''''
--	delete @tmp where LTRIM(ISNULL(CodeRow,'''')) = ''''
--end
--
--
--'
--
--set @cStr = case when @Code = 0 then '
--select ' else '
--select Cod,0 as OrderRow,
--'
--end
--
--set @cStr2 = ''
--set @cTmp = ''
--OPEN SEL_CURSOR
--FETCH NEXT FROM SEL_CURSOR INTO @LinkCol, @ColType, @IsEdited,@orders_col
----set @Orders = 1
--set @Orders =@orders_col
--while @@fetch_status = 0
--begin
--	if @Orders < 20
--	begin
----select * from #tmp_col where link_col=@LinkCol
--		if dbo.RO_AccessColByLink(@LinkCol) > 0 and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
--		begin
--			set @cStr = @cStr + @NameCol + LTRIM(STR(@Orders)) + '=min(case when T.Link_Col=' + LTRIM(STR(@LinkCol)) + ' then ' + @RGB_itog + ' else '+@RGB_simple+' end),
--'
--		end
--		else begin -- нет доступа к колонке
--			set @cStr = @cStr + @NameCol + LTRIM(STR(@Orders)) + '=' + @RGB_zapret + ',
--'		end
--	end
--	else begin
--		if dbo.RO_AccessColByLink(@LinkCol) > 0 and (not exists(select * from #tmp_col where link_col=@LinkCol)  or @web<>1)
--		begin
--			set @cStr2 = @cStr2 + @NameCol + LTRIM(STR(@Orders)) + '=min(case when T.Link_Col=' + LTRIM(STR(@LinkCol)) + ' then ' + @RGB_itog + ' else '+@RGB_simple+' end),
--'
--		end
--		else begin -- нет доступа к колонке
--			set @cStr2 = @cStr2 + @NameCol + LTRIM(STR(@Orders)) + '=' + @RGB_zapret + ',
--'		end
--	end
--	FETCH NEXT FROM SEL_CURSOR INTO @LinkCol, @ColType, @IsEdited,@orders_col
----	set @Orders = @Orders + 1
--	set @Orders =@orders_col
--
--end
--if @cStr2 <> ''
--begin
--	set @cStr2 = LEFT(@cStr2, LEN(@cStr2) - 3)
--end
--else begin
--	set @cStr = LEFT(@cStr, LEN(@cStr) - 3)
--end
--
--set @cStr2 = @cStr2 + '
--'+case when @tmp_table<>'' then ' into '+@tmp_table else '' end +' 
--from  @Code RD
-- left merge join @tmp T on T.CodeRow = RD.Cod
--group by RD.Cod'
--
--CLOSE SEL_CURSOR
--DEALLOCATE SEL_CURSOR
--
--print @cStr1
--print @cStr
--print @cStr2
--print @cStr
--print @cStr2
----print   ') A
----group by Cod, OrderRow order by cod
----'
----print ' drop table #tmp'
--execute(@cStr1 + @cStr + @cStr2)

end 




GO
GRANT EXECUTE ON dbo.[RO_TOTAL_CELLS] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO

/* © Кейсистемс (Keysystems), 2010 Процедура формирования строк и значений формы 0503125 */

CREATE PROCEDURE dbo.RT_CALC_0503125M_ITOG_2015
@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(100),
@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), inn varchar(20), ppp char(3), el_bud char(2), okato char(14), 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, inn, ppp, okato, el_bud, KBK, Code_acc, summa_db, summa_kr, korr_acc, dnd, link, key_prov, tabsource)
select
coalesce(rd1.Str_Val,''), --Наименование
coalesce(rd2.Str_Val,''),	--Инн
substring(coalesce(rd3.Str_Val,''),1,3), -- Глава по БК
coalesce(rd4.Str_Val,''),				 -- Код ОКТМО
substring(coalesce(rd5.Str_Val,''),1,2), -- Код элемента бюджета
--substring(coalesce(rd6.Str_Val,''),1,3), -- АДМ
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(rd6.Str_Val,'')),3)+left(left(ltrim(coalesce(rd7.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(rd6.Str_Val,'')),3)+left(left(ltrim(coalesce(rd7.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(rd6.Str_Val,'')),3)+left(left(ltrim(coalesce(rd7.Str_Val,'')),3)+'00000000000000',14)
when @table = 3 and right(rtrim(@cAccount),8) in ('30111000','30131000','30141000','30151000','30121000')
then right('000'+rtrim(coalesce(rd6.Str_Val,'')),3)+left(left(ltrim(coalesce(rd7.Str_Val,'')),14)+'00000000000000',14)
when @table = 3 and right(rtrim(@cAccount),8) in ('30111810','30131810', '30111710', '30121710', '30121810')
then right('000'+rtrim(coalesce(rd6.Str_Val,'')),3)+left(left(ltrim(coalesce(rd7.Str_Val,'')),10)+'00000000000000',14)
else right('000'+rtrim(coalesce(rd6.Str_Val,'')),3)+left(left(ltrim(coalesce(rd7.Str_Val,'')),4)+'00000000000000',14)
end,
case WHEN right(rtrim(@cAccount),8) in ('30406000')
THEN CASE WHEN isnull(rd8.Float_Val,0.00) <> 0
THEN LEFT(@cAccount,6) + '830'
ELSE LEFT(@cAccount,6) + '730' END 
ELSE @cAccount
END,
isnull(rd8.Float_Val,0.00),
isnull(rd9.Float_Val,0.00),
substring(coalesce(rd10.Str_Val,''),1,9),
case when cast(rtrim(isnull(rd15.Str_Val,'')) as varchar) not in (0,1) then NULL else cast(rtrim(isnull(rd15.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 rd15 on rd15.link_sf = @LSF and rd15.Code_Row = srows.Code_Row and 15 = (select Orders from dbo.report_coloumns where link_col = rd15.link_col) and rd15.link_col = (select link_col from dbo.report_coloumns where Orders = 15 and Link_Table = @iLink_Table)

-- исключение, добавить сумму по '30406000'
INSERT @table2 (Name_bp, INN, ppp, el_bud, okato, KBK, Code_Acc, summa_db, summa_kr,
       korr_acc, dnd, link, key_prov, tabsource)
SELECT Name_bp, INN, 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, INN, ppp, okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, link, key_prov, tabsource)
select
coalesce(rd1.Str_Val,''),
coalesce(rd2.Str_Val,''),
substring(coalesce(rd3.Str_Val,''),1,3),
substring(coalesce(rd4.Str_Val,''),1,8),
substring(coalesce(rd5.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(rd6.Str_Val,'')),3)+right('0000'+rtrim(coalesce(rd7.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') and @cSGU in ('710','810')) or
(@cSinth = '302' and @cAnalit = '51' and @cSGU = '830'))
then right('0000000'+rtrim(coalesce(rd8.Str_Val,'')),7) + '000'
else '0000000000'
end,
case WHEN right(rtrim(@cAccount),8) in ('30406000')
THEN CASE WHEN isnull(rd10.Float_Val,0.00) <> 0
THEN LEFT(@cAccount,6) + '830'
ELSE LEFT(@cAccount,6) + '730' END 
ELSE @cAccount
END,
isnull(rd10.Float_Val,0.00),
isnull(rd11.Float_Val,0.00),
substring(coalesce(rd12.Str_Val,''),1,9),
case when cast(rtrim(isnull(rd17.Str_Val,'')) as varchar) not in (0,1) then NULL else cast(rtrim(isnull(rd17.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)
left join #report_dinamics as rd17 on rd17.link_sf = @LSF and rd17.Code_Row = srows.Code_Row and 17 = (select Orders from dbo.report_coloumns where link_col = rd17.link_col) and rd17.link_col = (select link_col from dbo.report_coloumns where Orders = 17 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 (INN, ppp,KBK,Code_Acc,summa_db,link)
select INN, 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 INN, ppp,KBK,Code_Acc
-- итоговые по неденежным
insert into @table2 (INN, 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 INN, 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 INN, 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 (INN, 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 INN, 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 INN, 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 (INN, ppp,KBK,Code_Acc,summa_kr,link)
select INN, 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 INN, ppp,KBK,Code_Acc
-- итоговые по неденежным
insert into @table2 (INN, 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 INN, 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 INN, 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 (INN, ppp,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_db,link)
select INN, 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 INN, ppp, el_bud,okato,Code_Acc
-- итоговые по неденежным
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select INN, 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 INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select INN, 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 INN, 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 INN, 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 (/*INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_db,link)
select INN, 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 INN, ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
--insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
if @code_form like '425_' begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp, el_bud,okato,Code_Acc,summa_db,link)
select INN, 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 INN, ppp, el_bud,okato,Code_Acc

end
-- итоговые по неденежным
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select INN, 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.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select INN, 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 INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc
end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_db,link)     select INN, 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 INN, ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select INN, 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 INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_db,link, kbk)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_db,link)
select INN, 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 INN, 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 ('31','41') and @cSGU = '000') or
(@cSinth = '302' and @cAnalit = '51' and @cSGU = '000' AND @code_form LIKE '%125%') 
or (@cSinth = '301' and @cAnalit in ('21') and @cSGU = '000' AND @code_form LIKE '%125%')
begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,link)
select INN, 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 INN, 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') 
or (@cSinth = '301' and @cAnalit in ('21') and @cSGU = '000')
-- итоговые. в том числе по номеру (коду) счета
IF @code_form LIKE '%425%'
   insert into @table2 (INN, ppp,el_bud,okato,Code_Acc,summa_kr,link)
   select INN, 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 INN, ppp,el_bud,okato,Code_Acc


-- 301X1000 ####################################################################################################
if (@cSinth = '301' and @cAnalit in ('11') and @cSGU = '000') 
-- итоговые. в том числе по номеру (коду) счета
IF @code_form LIKE '%125%'
   insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,link)
   select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc
ELSE
   insert into @table2 (INN, ppp,el_bud,okato,Code_Acc,summa_kr,link)
   select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_kr,link)
select INN, 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 INN, ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
if @code_form like '425_' begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_kr,link)
select INN, 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 INN, ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
if @code_form like '425_' begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc
end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,Code_Acc,summa_kr,link)
select INN, 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 INN, ppp,el_bud,okato,Code_Acc
-- итоговые по неденежным
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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') 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select INN, 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 INN, 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') 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.INN, Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (INN, ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select INN, 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 INN, 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 < 10 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,6,9) then 0.0000
when @i = 7 then coalesce(summa_db,0.0000)
when @i = 8 then coalesce(summa_kr,0.0000)
end),
@str_val =
(case when @i in (7,8) then ''
when @i = 1 then cast(coalesce(Name_bp,'') as varchar (250))
when @i = 2 then cast(coalesce(INN,'') as varchar (20))
when @i = 3 then cast(coalesce(ppp,'') as varchar (250))
when @i = 4 then cast(coalesce(okato,'') as varchar (250))
when @i = 5 then cast(coalesce(el_bud,'') as varchar (250))
when @i = 6 then cast(coalesce(KBK,'')+coalesce(Code_acc,'') as varchar (250))
when @i = 9 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_2015] TO PUBLIC

GO


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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=140110180,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=140110180,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'140110180'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '140110180', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '140110180', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', '', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.401.10','','180',2,1,'АДМ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.401.10','','180',12,1,'АДМ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.401.10','','180','',12,1,'АДМ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.401.10','','180','',2,1,'АДМ',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=240120241,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=240120241,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'240120241'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '240120241', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '240120241', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'2.401.20','','241','',1,1,'АДМ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','2.401.20','','241',1,1,'АДМ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=240110180,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=240110180,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'240110180'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '240110180', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '240110180', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'2.401.10','','180','',2,1,'АДМ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'2.401.10','','180','',12,1,'АДМ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','2.401.10','','180',12,1,'АДМ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','2.401.10','','180',2,1,'АДМ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=230404000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=230404000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'230404000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '230404000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '230404000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'2.304.04','','','',2,1,'ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'2.304.04','','','',12,1,'ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'2.304.04','','','',1,1,'ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','2.304.04','','',1,1,'ДЕН',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','2.304.04','','',12,1,'ДЕН',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','2.304.04','','',2,1,'ДЕН',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=140120251,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=140120251,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'140120251'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '140120251', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '140120251', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.401.20','','251','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.401.20','','251',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120551560,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120551560,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120551560'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120551560', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120551560', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.205.51','','560','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.205.51','','560','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.205.51','','560',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.205.51','','560',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=140110151,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=140110151,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'140110151'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '140110151', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '140110151', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.401.10','','151',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.401.10','','151',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.401.10','','151','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.401.10','','151','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130404000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130404000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130404000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '130404000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130404000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.304.04','','','',12,1,'ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.304.04','','','',1,1,'ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.304.04','','','',2,1,'ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.304.04','','',1,1,'ДЕН',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.304.04','','',12,1,'ДЕН',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.304.04','','',2,1,'ДЕН',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130251830,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130251830,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130251830'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '130221830', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130251830', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.302.51','','830','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.302.51','','830','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.302.51','','830',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.302.51','','830',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130251000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130251000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130251000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '130221000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130251000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.302.51','','',12,3,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.302.51','','',1,3,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130111810,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130111810,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130111810'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '130111810', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130111810', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.11','','810','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.11','','810','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.11','','810','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.11','','810',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.11','','810',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.11','','810',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130112810,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130112810,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130112810'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '130112810', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130112810', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.12','','810','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.12','','810','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.12','','810','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.12','','810',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.12','','810',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.12','','810',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130113810,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130113810,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130113810'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '130113810', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130113810', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.13','','810','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.13','','810','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.13','','810','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.13','','810',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.13','','810',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.13','','810',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130111710,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130111710,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130111710'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '130111710', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130111710', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.11','','710','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.11','','710','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.11','','710','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.11','','710',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.11','','710',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.11','','710',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130112710,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130112710,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130112710'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '130112710', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130112710', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.12','','710','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.12','','710','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.12','','710','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.12','','710',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.12','','710',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.12','','710',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130113710,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130113710,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130113710'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '130113710', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130113710', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.13','','710','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.13','','710','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.13','','710','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.13','','710',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.13','','710',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.13','','710',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130111000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130111000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130111000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '130111000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130111000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.11','','',2,3,'АДМ,ОКАТО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.11','','',12,3,'АДМ,OКАТO,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.11','','',1,3,'АДМ,OКАТO,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130112000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130112000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130112000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '130112000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130112000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.12','','',2,3,'АДМ,OКАТO,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.12','','',12,3,'АДМ,ОКАТО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.12','','',1,3,'АДМ,OКАТO,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130113000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130113000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130113000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '130113000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130113000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.13','','',2,3,'АДМ,OКАТO,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.13','','',12,3,'АДМ,OКАТO,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.13','','',1,3,'АДМ,OКАТO,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120711640,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120711640,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120711640'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120711640', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120711640', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.11','','640','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.11','','640','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.11','','640','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.11','','640',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.11','','640',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.11','','640',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120711540,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120711540,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120711540'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120711540', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120711540', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.11','','540',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.11','','540',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.11','','540',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.11','','540','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.11','','540','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.11','','540','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120711000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120711000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120711000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120711000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120711000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.11','','','',12,3,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.11','','','',2,3,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.11','','','',1,3,'',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120712640,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120712640,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120712640'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120712640', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120712640', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.12','','640','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.12','','640','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.12','','640','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.12','','640',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.12','','640',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.12','','640',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120712540,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120712540,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120712540'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120712540', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120712540', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.12','','540','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.12','','540','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.12','','540','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.12','','540',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.12','','540',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.12','','540',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120712000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120712000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120712000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120712000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120712000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.12','','','',1,3,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.12','','','',12,3,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.12','','','',2,3,'',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120713640,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120713640,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120713640'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120713640', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120713640', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.13','','640','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.13','','640','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.13','','640','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.13','','640',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.13','','640',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.13','','640',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120713000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120713000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120713000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120713000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120713000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.13','','','',1,3,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.13','','','',12,3,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.13','','','',2,3,'',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120713540,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120713540,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120713540'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120713540', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120713540', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.13','','540','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.13','','540','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.13','','540','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.13','','540',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.13','','540',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.13','','540',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120651660,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120651660,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120651660'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120651660', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120651660', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.206.51','','660',0,1,'',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.206.51','','660',0,1,'',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.206.51','','660','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.206.51','','660','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120651560,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120651560,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120651560'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120651560', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120651560', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.206.51','','560',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.206.51','','560','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.206.51','','560','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120651000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120651000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120651000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120651000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120651000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.206.51','','','',1,3,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.206.51','','','',12,3,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.206.51','','','',2,3,'',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120551660,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120551660,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120551660'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120551660', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120551660', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.205.51','','660','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.205.51','','660',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.205.51','','660','',12,1,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.205.51','','660',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ,ДЕН',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=140120241,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=140120241,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'140120241'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '140101241', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '140120241', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.401.20','','241',1,1,'АДМ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.401.20','','241','',1,1,'АДМ',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120551000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120551000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120551000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC', '120551000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120551000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.205.51','','','',2,3,'',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130121000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130121000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130121000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130121000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.21','','',2,3,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.21','','',12,3,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.21','','',1,3,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130131000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130131000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130131000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130131000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.31','','',2,3,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.31','','',12,3,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.31','','',1,3,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130121710,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130121710,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130121710'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130121710', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.21','','710','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.21','','710','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.21','','710','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.21','','710',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.21','','710',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.21','','710',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130121810,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130121810,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130121810'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130121810', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.21','','810','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.21','','810','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.21','','810','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.21','','810',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.21','','810',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.21','','810',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130131710,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130131710,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130131710'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130131710', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.31','','710','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.31','','710','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.31','','710','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.31','','710',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.31','','710',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.31','','710',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130131810,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=130131810,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'130131810'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '130131810', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.31','','810','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.31','','810','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.301.31','','810','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.31','','810',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.31','','810',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.301.31','','810',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120721000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120721000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120721000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120721000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.21','','','',1,3,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.21','','','',12,3,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.21','','','',2,3,'',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120731000,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120731000,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120731000'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120731000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.31','','','',1,3,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.31','','','',12,3,'',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.31','','','',2,3,'',0,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120721540,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120721540,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120721540'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120721540', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.21','','540','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.21','','540','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.21','','540','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.21','','540',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.21','','540',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.21','','540',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120721640,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120721640,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120721640'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120721640', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.21','','640','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.21','','640','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.21','','640','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.21','','640',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.21','','640',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120731540,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120731540,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120731540'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120731540', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.31','','540','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.31','','540','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.31','','540','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.31','','540',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.31','','540',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.31','','540',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
GO
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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120731640,REPORTS_ATR_PRP=500'


	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 = '0503125M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = 'REPORTS_ATR_ACC_2011=120731640,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,'120731640'
	from dbo.REPORT_FORMS where CODE = '0503125M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ACC_2011', '120731640', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.31','','640','',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 8
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.31','','640','',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 10
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.207.31','','640','',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 11
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.31','','640',1,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.31','','640',12,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 9
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.207.31','','640',2,1,'АДМ,ОКТМО,ЭЛЕМЕНТ',1,''
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(100),
                              [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(100)' 
                                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(100)),4)+'''),'$CODE3$','''+RIGHT(''000''+CAST(ROW_NUMBER() OVER (ORDER BY [ORDERS],[CODE]) AS VARCHAR(100)),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
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (фев  3 2016  4:04:20:530PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503127M (Отчет об исполнении бюджета (распорядитель/получатель))
-- Дата ввода : 20160101
-- Дата окончания действия :
-- Версия : 2016-02-03 16:04:20.527
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0503127M' AND [START_DATE] = '20160101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2016-02-03 16:04:20.527',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0503127M',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0503127M'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20160101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SMETA'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Отчет об исполнении бюджета (распорядитель/получатель)',@vcNEW_FORM_CODE,@dNEW_START_DATE,4,1,1,1,18186,'RA_EXPORT_FORM_STANDART#RA_IMPORT_FORM_127',0,0,'19000101',NULL,'191н'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'svodprint_page_itog_127()','sv_0503127G_20090101.bas','','kirrepmakermultisheet.xls','sv_0503127M_20160101.xlt','',NULL,'RA_EXPORT_FORM_STANDART#RA_IMPORT_FORM_127',0,'COL2 + ''|$ADM$|'' + COL3 + ''|'' + STR(COL4) + ''|'' + STR(COL5) + ''|'' + STR(COL6) + ''|'' + STR(COL7) + ''|'' + STR(COL8) + ''|'' + STR(COL9)+''|'' # COL2 + ''|$ADM$|'' + COL3 + ''|'' + COL4 + ''|'' + COL5 + ''|'' + STR(COL6) + ''|'' + STR(COL7) + ''|'' + STR(COL8) + ''|'' + STR(COL9) + ''|'' + STR(COL10) + ''|'' + STR(COL11) + ''|'' + STR(COL12) + ''|'' + STR(COL13) + ''|'' + STR(COL14)+''|'' # RTRIM(COL2)+ ''|$ADM$|'' + RTRIM(COL3) + ''|'' + STR(COL4) + ''|'' + STR(COL5) + ''|'' + STR(COL6) + ''|'' + STR(COL7) + ''|'' + STR(COL8) + ''|'' + STR(COL9)+''|''','C1 + ''|'' + C3 + ''|'' + C4 + ''|'' + C5 + ''|'' + C6 + ''|''  + C7 + ''|'' + C8 + ''|'' + C9 # C1 + ''|'' + C3 + C4 + C5 + C6 + ''|'' + C7 + ''|'' + C8 + ''|'' + C9 + ''|'' + C10 + ''|'' + C11 + ''|'' + C12 + ''|'' + C13 + ''|'' + C14 # C1 +  C3 + ''|''  + C4 + ''|''  + C5 + ''|''  + C6 + ''|''  + C7 + ''|''  + C8 + ''|''  + C9',NULL,'227       ','REPORTS_ATR_ADM,REPORTS_ATR_VIDDEYAT,REPORTS_FILTER_KBK,REPORTS_ATR_PRP',NULL,'RO_PRINT_127_ITOG_16','|sv_0503127G_20090101_new.xlt',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Доходы бюджета', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,1,1000,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,2,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Код дохода по КД',@iLINK_TABLE,1,1,3,0,17,1,'R_SPR_DOH_17_2011','COL1,COL2,COL3','LONG_NAME,CODE_STR,CODE','NNNNNNNNNNNNNNNNN',6,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Утвержденные бюджетные назначения',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Исполнено через финансовые органы',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Исполнено через банковские счета',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Исполнено через некассовые операции',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Исполнено итого',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Неисполненные назначения',@iLINK_TABLE,1,0,9,9,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Доходы бюджета', @iLINK_FORM,1, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RB_CALC_FORM_0503127G09 @lsf, 1, @dateEndPeriod, @depLink
CALC_SKELET=sql.call("dbo.RO_CALC_SKELET",m.cAlias,0x0,''0503127M'',1,''20110101'')
EXPORT_CODE_DOP=127','-1#LEFT(CODE,3)=''850''
1#LEFT(CODE,3)=''790''',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Расходы бюджета', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,1,1500,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,2,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'РЗПР',@iLINK_TABLE,0,1,0,0,4,1,'R_SPR_RZPR_2011','COL3','CODE','NNNN',NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'ЦСР',@iLINK_TABLE,0,1,0,0,10,1,'R_SPR_CSR_USER_2016','COL4','CODE','NNNNNNNNNN',NULL,NULL,'dbo.RO_KBK_ORG_IS_VIEW(link, org, budg,%link_org%, %link_budg%, ''20110101'')=1 AND %date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'ВР',@iLINK_TABLE,0,1,0,0,3,1,'R_SPR_VR_USER_2011','COL5,COL1,COL2','CODE,NAME,CODE_STR','NNN',NULL,NULL,'dbo.RO_KBK_ORG_IS_VIEW(link, org, budg,%link_org%, %link_budg%, ''20110101'') = 1 AND %date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Утвержденные бюджетные назначения',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Лимиты бюджетных обязательств',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Исполнено через финансовые органы',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Исполнено через банковские счета',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Исполнено через некассовые операции',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Исполнено итого',@iLINK_TABLE,1,0,9,9,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Неисполнено по асигнованиям',@iLINK_TABLE,1,0,10,10,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Неисполнено по лимитам бюджетных обязательств',@iLINK_TABLE,1,0,11,11,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Код расхода по ППП, по ФКР, КЦСР, КВР, ЭКР',@iLINK_TABLE,1,1,2,0,17,1,'R_SPR_RASH_117_2016','COL1,COL2,COL14','NAME,CODE_STR,CODE',NULL,7,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Расходы бюджета', @iLINK_FORM,2, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RB_CALC_FORM_0503127G09 @lsf, 2, @dateEndPeriod, @depLink
CALC_SKELET=sql.call("dbo.RO_CALC_SKELET",m.cAlias,0x0,''0503127M'',2,''20110101'')
KEY_FOX=PADR(RTRIM(COL3),4,''0'')+PADR(RTRIM(COL4),10,''0'')+PADR(RTRIM(COL5),3,''0'')
KEY_WEB=LEFT(RTRIM(isnull(COL3,''''))+''0000'',4)+LEFT(RTRIM(ISNULL(COL4,''''))+''0000000000000'',10)+LEFT(RTRIM(ISNULL(COL5,''''))+''000'',3)
SPLIT=COL3=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,4)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',5,10)#COL5=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',15,3)
FILTER_GRID=Рзпр#COL3|ЦСР#COL4|ВР#COL5
AUTO_SPR_FORM=R_SPR_RASH_117_2016
AUTO_SPR_NAME_UPD=''COL5=SUBSTRING(CODE,15,3)=000#COL4=SUBSTRING(CODE,5,10)=0000000#COL3=SUBSTRING(CODE,1,4)=0000'', ''report_kbk'', ''CODE'', ''LONG_NAME'',''code_form=''''R_SPR_RASH_117_2016'''' and isnull(T.long_name,'''''''')=''''''''''
AUTOFILL_MASK=XXXXXXXXXXXXXXXXXddd
AUTO_SPR_CHECK= exists(select * from R_SPR_RZPR_2011 where code = SUBSTRING(T.code,1,4))  and ((exists(select * from R_SPR_CSR_USER_2016 where code = SUBSTRING(T.code,5,10)) and exists(select * from dbo.R_SPR_VR_2011 where code = SUBSTRING(T.code,15,3))) OR ISNULL((SELECT Val_int FROM dbo.report_options WHERE Razdel = ''COMMON'' AND Code = ''ITOG_117''),0) =1) and T.code <> ''00000000000000000'' and not (LEFT(T.code,4) = ''9600'' and SUBSTRING(T.Code, 15,3) <> ''000'') and not (LEFT(T.code,4) = ''7900'' and SUBSTRING(T.Code, 15,3) <> ''000'')
 
AUTO_SPR_CODE_STR=case when left(T.code,4) <> ''7900'' then ''200'' else ''450'' end
AUTO_SPR_PARENT=5#left(T.Code,14) + XXX','-1#LEFT(CODE,3)=''960''
1#LEFT(CODE,3)=''790''',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Источники финансирования дефицита бюджета', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,2000,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,0,1,2,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Код источника финансирования по бюджетной классификации',@iLINK_TABLE,0,1,3,0,50,1,'R_SPR_IST_127_2011','COL1,COL2,COL3','LONG_NAME,CODE_STR,CODE_IST','NN NN NN NN NN NNNN NNN',NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Утвержденные бюджетные назначения',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Исполнено через финансовые органы',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Исполнено через банковские счета',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Исполнено через некассовые операции',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Исполнено итого',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Неисполненные назначения',@iLINK_TABLE,1,0,9,9,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Код строки и Код источника',@iLINK_TABLE,1,1,1,0,0,1,'R_SPR_IST_127_2011','COL1,COL2,COL3,COL10','LONG_NAME,CODE_STR,CODE_IST,CODE',NULL,1,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Источники финансирования дефицита бюджета', @iLINK_FORM,3, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RB_CALC_FORM_0503127G09 @lsf, 3, @dateEndPeriod, @depLink
CALC_SKELET=sql.call("dbo.RO_CALC_SKELET",m.cAlias,0x0,''0503127M'',3,''20110101'')
KEY_FOX=PADR(RTRIM(COL2),3,''0'')+PADR(RTRIM(COL3),17,''0'')
KEY_WEB=LEFT(RTRIM(ISNULL(COL2,''''))+''000'',3)+LEFT(RTRIM(isnull(COL3,''''))+''00000000000000000000'',17)
SPLIT=COL2=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000000'',1,3)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000'',4,17)
KBK=4,5,6,7,-8,-9','-1#LEFT(CODE,6)=''500900''',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.1гр.9 =  т.1гр.4 -  т.1гр.8',3,3,1,'20111007','COL(4)<>convert(float,0) and COL(4) is not null','','','0503127M','20160101','','=',4,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'т.2гр.11 =  т.2гр.5 -  т.2гр.9 Дипазон строк:Кроме строки 7900 0000000 000 000',3,2,1,'20111007','SUBSTRING(CODE,1,4)<>''7900'' and COL(8)<>convert(float,0) and COL(8) is not null','','Кроме строки 7900 0000000 000 000','0503127M','20160101','','=',4,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'т.2гр.9 =  т.2гр.6 +  т.2гр.7 +  т.2гр.8',1,1,1,'20111007','','','','0503127M','20160101','','=',3,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'т.3гр.8 =  т.3гр.5 +  т.3гр.6 +  т.3гр.7',1,1,1,'20111007','','','','0503127M','20160101','','=',3,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'т.2гр.10 =  т.2гр.4 -  т.2гр.9 Дипазон строк:Кроме строки 7900 0000000 000 000',3,2,1,'20111007','SUBSTRING(CODE,1,4)<>''7900'' and COL(7)<>convert(float,0) and COL(7) is not null','','Кроме строки 7900 0000000 000 000','0503127M','20160101','','=',4,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.2Фильтр:стр.96000000000000000 =  т.2Фильтр:не подитоги +  т.2Фильтр:если нет, то подитоги 200 +  т.2Фильтр:если нет, то подитоги 300,500,600 Дипазон колонок:4,5,6,7,8,0,0,0',1,101,1,'20120124','','7,8,9,10,11,-12,-13,-14','','0503127M','20160101','','=',0,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.1гр.8 =  т.1гр.5 +  т.1гр.6 +  т.1гр.7',1,2,1,'20111007','','','','0503127M','20160101','','=',3,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'т.2стр.79000000000000000гр.6 =  т.1стр.85000000000000000гр.5 -  т.2стр.96000000000000000гр.6',1,112,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'т.2стр.79000000000000000гр.7 =  т.1стр.85000000000000000гр.6 -  т.2стр.96000000000000000гр.7',1,112,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'т.2стр.79000000000000000гр.8 =  т.1стр.85000000000000000гр.7 -  т.2стр.96000000000000000гр.8',1,112,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(11,NULL,0,NULL,11,7,0,0,0,'т.2стр.79000000000000000гр.6 =  0 -  т.3стр.50090000000000000000гр.5',0,0,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(12,NULL,0,NULL,12,7,0,0,0,'т.2стр.79000000000000000гр.7 =  0 -  т.3стр.50090000000000000000гр.6',0,0,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'т.2стр.79000000000000000гр.8 =  0 -  т.3стр.50090000000000000000гр.7',0,0,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(14,NULL,0,NULL,14,7,0,0,0,'т.2стр.79000000000000000гр.9 =  0 -  т.3стр.50090000000000000000гр.8',0,0,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(15,NULL,0,NULL,15,7,0,0,0,'т.2стр.79000000000000000гр.9 =  т.1стр.85000000000000000гр.8 -  т.2стр.96000000000000000гр.9',1,112,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(16,NULL,0,NULL,16,7,0,0,0,'т.2стр.79000000000000000гр.5 =  0',0,110,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(17,NULL,0,NULL,17,7,0,0,0,'т.2стр.79000000000000000гр.10 =  0',0,110,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(18,NULL,0,NULL,18,7,0,0,0,'т.2стр.79000000000000000гр.11 =  0',0,110,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'т.1гр.9 =  т.1гр.4',3,4,1,'20111007','COL(4)=convert(float,0) or COL(4) is null','','','0503127M','20160101','','=',4,'','')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'т.3гр.9 =  т.3гр.4',3,3,1,'20111007','COL(4)=convert(float,0) or COL(4) is  null','','','0503127M','20160101','','=',4,'','')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'т.2гр.11 =  т.2гр.5',3,3,1,'20111007','SUBSTRING(CODE,1,4)<>''7900'' and (COL(8)=convert(float,0) or COL(8) is null)','','','0503127M','20160101','','=',4,'','')
INSERT #A VALUES(22,NULL,0,NULL,22,7,0,0,0,'т.2гр.10 =  т.2гр.4',3,3,1,'20111007','SUBSTRING(CODE,1,4)<>''7900'' and (COL(7)=convert(float,0) or COL(7) is null)','','','0503127M','20160101','','=',4,'','')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'т.3гр.9 =  т.3гр.4 -  т.3гр.8',3,12,1,'20111007','left(CODE,3) in (''520'',''620'',''700'') and COL(4)<>convert(float,0) and COL(4) is not null','','','0503127M','20160101','','=',4,'','')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'т.1гр.4Фильтр:Подитоги по регион. кодам =  т.1гр.4Фильтр:Региональные кода',1,0,1,'20111122','','','','0503127M','20160101','','=',0,'','')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'т.2стр.79000000000000000гр.4 =  0',0,110,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'т.3Фильтр:Подитоги по регион. кодам =  т.3Фильтр:Региональные кода Дипазон колонок:4,5,6,7,0,0',1,0,1,'20111122','','4,5,6,7,-8,-9','','0503127M','20160101','','=',0,'','')
INSERT #A VALUES(27,NULL,0,NULL,27,7,0,0,0,'т.3стр.81106000000000000000гр.4 =  0',1,0,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(28,NULL,0,NULL,28,7,0,0,0,'т.3стр.81207000000000000000гр.4 =  0',1,0,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(29,NULL,0,NULL,29,7,0,0,0,'т.3стр.81005000000000000000гр.4 =  0',1,0,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(30,NULL,0,NULL,30,7,0,0,0,'т.3стр.82109000000000000000гр.4 =  0',1,0,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(31,NULL,0,NULL,31,7,0,0,0,'т.3стр.82201000000000000000гр.4 =  0',1,0,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(32,NULL,0,NULL,32,7,0,0,0,'т.3стр.82008000000000000000гр.4 =  0',1,0,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(33,NULL,0,NULL,33,7,0,0,0,'т.3стр.80004000000000000000гр.4 =  0',1,0,1,'20111007','','','','0503127M','20160101','','=',1,'','')
INSERT #A VALUES(34,NULL,0,NULL,34,7,0,0,0,'т.1гр.5Фильтр:Подитоги по регион. кодам =  т.1гр.5Фильтр:Региональные кода',1,0,1,'20111122','','','','0503127M','20160101','','=',0,'','')
INSERT #A VALUES(35,NULL,0,NULL,35,7,0,0,0,'т.1гр.6Фильтр:Подитоги по регион. кодам =  т.1гр.6Фильтр:Региональные кода',1,0,1,'20111122','','','','0503127M','20160101','','=',0,'','')
INSERT #A VALUES(36,NULL,0,NULL,36,7,0,0,0,'т.1гр.7Фильтр:Подитоги по регион. кодам =  т.1гр.7Фильтр:Региональные кода',1,0,1,'20111122','','','','0503127M','20160101','','=',0,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 36
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','','1',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','','1',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','','1',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','13','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(2,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(3,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(3,4,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','10','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','','3',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','','3',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(4,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','','3',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(4,4,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','','3',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(5,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','96000000000000000','code = ''96000000000000000''','стр.96000000000000000','CODE','','','','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','00000000000000000200','right(rtrim(code),3) not in (''200'',''000'',''210'',''220'',''230'',''240'',''250'',''260'',''300'',''500'',''600'')','не подитоги','''96000000000000000''','','','','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(6,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','right(rtrim(code),3) in (''210'',''220'',''230'',''240'',''250'',''260'') and not exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,16) = LEFT(CODE,16) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,17,1) <> ''0'' and round(RD1.float_val,2) <> 0.00)','если нет, то подитоги 200','''96000000000000000''','','','','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(6,4,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','right(rtrim(code),3) in (''300'',''500'',''600'') and not exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,15) = LEFT(CODE,15) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,16,2) <> ''00'' and round(RD1.float_val,2) <> 0.00)','если нет, то подитоги 300,500,600','''96000000000000000''','','','','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','','1',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','','1',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(7,3,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','','1',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(7,4,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','','1',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','8','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','85000000000000000','','','','','','5','','1',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(8,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','96000000000000000','','','','','','8','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','9','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','85000000000000000','','','','','','6','','1',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(9,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','96000000000000000','','','','','','9','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','10','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','85000000000000000','','','','','','7','','1',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(10,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','96000000000000000','','','','','','10','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','8','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(11,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','50090000000000000000','','','','','','5','','3',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','9','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(12,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','50090000000000000000','','','','','','6','','3',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','10','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(13,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','50090000000000000000','','','','','','7','','3',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','11','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(14,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','50090000000000000000','','','','','','8','','3',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','11','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','85000000000000000','','','','','','8','','1',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(15,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','96000000000000000','','','','','','11','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','7','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','12','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','13','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','','1',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','','1',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','','3',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','','3',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','13','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','','2',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','','2',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','','3',NULL,0,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','','3',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(23,3,3,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','','3',NULL,0,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0)','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0) and exists(select top 1 * from dbo.R_SPR_DOH_17_2011 SPR where SPR.Code = LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3))','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','4','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','79000000000000000','','','','','','6','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,14,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,13) = LEFT(CODE,13) and SUBSTRING(RD1.Code_Row,18,3) = SUBSTRING(CODE,18,3) and RD1.Link_Col in (select Link_Col from report_coloumns C5 where C5.Link_Table = (select top 1 B5.Link_Table from report_coloumns B5 where B5.Link_Col = B.Link_Col)) and substring(RD1.Code_Row,14,4) <> ''0000'')','Подитоги по регион. кодам','LEFT(CODE,13)+''0000'' + RIGHT(RTRIM(CODE),3)','','','','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,14,4)<>''0000''','Региональные кода','LEFT(CODE,13)+''0000'' + RIGHT(RTRIM(CODE),3)','','','','','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','81106000000000000000','','','','','','4','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','81207000000000000000','','','','','','4','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','81005000000000000000','','','','','','4','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','82109000000000000000','','','','','','4','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','82201000000000000000','','','','','','4','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','82008000000000000000','','','','','','4','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','80004000000000000000','','','','','','4','','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0)','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','5','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0) and exists(select top 1 * from dbo.R_SPR_DOH_17_2011 SPR where SPR.Code = LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3))','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','5','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0)','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','6','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0) and exists(select top 1 * from dbo.R_SPR_DOH_17_2011 SPR where SPR.Code = LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3))','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','6','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4) = ''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0)','Подитоги по регион. кодам','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','7','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,11,4)<>''0000'' and exists(select top 1 * from report_dinamics_all RD1 where RD1.Link_SF = A.Link_SF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and SUBSTRING(RD1.Code_Row,15,3) = SUBSTRING(CODE,15,3) and RD1.Link_Col = B.Link_Col and substring(RD1.Code_Row,11,4) <> ''0000'' and RD1.float_val<>0) and exists(select top 1 * from dbo.R_SPR_DOH_17_2011 SPR where SPR.Code = LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3))','Региональные кода','LEFT(CODE,10)+''0000'' + RIGHT(RTRIM(CODE),3)','','','7','','1',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 92
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '999999    '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'999999','формы отчетности',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2016-02-03 16:04:20.527',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 = '2016-02-03 16:04:20.527'
	BEGIN
		SELECT @vcMessage = 'Форма 0503127M с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503127M с версией от ' + @vcMessage + ' не может быть обновлена версией от 2016-02-03 16:04:20.527. Обновление отклонено.'
	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

------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник целевых статей С КОДОМ R_SPR_CSR_2016------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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', 3, 'isnull(Long_name, name)', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ЦСР_2016'' and Code not in (select KK.Code from dbo.report_kbk KK where KK.Code_form =''ЦСР_2016_USER'')')

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ЦСР_2016_USER''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_CSR_2016'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_CSR_2016', 'Справочник целевых статей', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник целевых статей (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_CSR_2016]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(isnull(Long_name, name)) as [NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ЦСР_2016' and Code not in (select KK.Code from dbo.report_kbk KK where KK.Code_form ='ЦСР_2016_USER') GROUP BY Code,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(isnull(Long_name, name)) as [NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ЦСР_2016_USER' GROUP BY Code,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_CSR_2016] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_2016')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_2016'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2016')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_2016', 'Справочник целевых статей', 224, (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_CSR_2016', NAME = 'Справочник целевых статей', ORDERS = '224', 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_CSR_2016'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2016_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_2016_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_2016_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_2016_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2016_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_2016_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_2016_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_2016_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2016_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_2016_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_2016_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_2016_Name'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016', 'TITLE', 'Справочник целевых статей'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_CSR_2016'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_CSR_2016'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016', 'SERVER_TABLE_NAME', 'R_SPR_CSR_2016'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_CSR_2016'''
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2016_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_2016', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_2016', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_2016', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_2016', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник федеральных целевых статей С КОДОМ R_SPR_CSR_FED_2016------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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', 3, 'isnull(Long_name, name)', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ЦСР_2016''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_CSR_FED_2016'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_CSR_FED_2016', 'Справочник федеральных целевых статей', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник федеральных целевых статей (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_CSR_FED_2016]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(isnull(Long_name, name)) as [NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ЦСР_2016' GROUP BY Code,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_CSR_FED_2016] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_FED_2016')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_FED_2016'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2016')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_FED_2016', 'Справочник федеральных целевых статей', 222, (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_CSR_FED_2016', NAME = 'Справочник федеральных целевых статей', ORDERS = '222', 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_CSR_FED_2016'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2016_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_FED_2016_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_FED_2016_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_FED_2016_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2016_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_FED_2016_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_FED_2016_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_FED_2016_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2016_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_FED_2016_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_FED_2016_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_FED_2016_Name'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016', 'TITLE', 'Справочник федеральных целевых статей'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_CSR_FED_2016'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_CSR_FED_2016'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016', 'SERVER_TABLE_NAME', 'R_SPR_CSR_FED_2016'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_CSR_FED_2016'''
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2016_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_FED_2016', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_FED_2016', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_FED_2016', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_FED_2016', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник целевых статей (общий для всех организаций) С КОДОМ R_SPR_CSR_USER_2016_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', 3, 'name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Org', 4, '', '', '0', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Budg', 5, '', '', '0', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_CSR_2016', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_CSR_USER_2016_2'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_CSR_USER_2016_2', 'Справочник целевых статей (общий для всех организаций)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник целевых статей (общий для всех организаций) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_CSR_USER_2016_2]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],0 as [ORG],0 as [BUDG],max(name) as [NAME],begin_date,end_date FROM R_SPR_CSR_2016 GROUP BY Code,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_CSR_USER_2016_2] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_USER_2016_2')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_USER_2016_2'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_2', 'Справочник целевых статей (общий для всех организаций)', 225, (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_CSR_USER_2016_2', NAME = 'Справочник целевых статей (общий для всех организаций)', ORDERS = '225', 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_CSR_USER_2016_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_2_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_2_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_2_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_2_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_2_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_2_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_2_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_2_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_2_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2_Org')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_2_Org', '', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_2_Org', NAME = '', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_2_Org'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2_Budg')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_2_Budg', '', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_2_Budg', NAME = '', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_2_Budg'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2', 'TITLE', 'Справочник целевых статей (общий для всех организаций)'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_CSR_USER_2016_2'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_CSR_USER_2016_2'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2', 'SERVER_TABLE_NAME', 'R_SPR_CSR_USER_2016_2'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_CSR_USER_2016_2'''
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_Org', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_Org', 'CONTROLSOURCE', 'm.cAlias + ".Org"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_Org', 'FIELD_DATA', 'Org'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_Budg', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_Budg', 'CONTROLSOURCE', 'm.cAlias + ".Budg"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_2_Budg', 'FIELD_DATA', 'Budg'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2016_2', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2016_2', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2016_2', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2016_2', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник региональных целевых статей (только для организаций) С КОДОМ R_SPR_CSR_USER_2016_1------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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, 'K.Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 3, 'coalesce(O.Long_Name, O.Name, K.Long_name, K.name)', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Org', 4, 'O.Link_Org', '', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Budg', 5, 'O.Link_Budg', '', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK K JOIN dbo.REPORT_KBK_ORG O on K.Link = O.Link_KBK', 'Code_Form = ''ЦСР_2016_USER''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_CSR_USER_2016_1'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_CSR_USER_2016_1', 'Справочник региональных целевых статей (только для организаций)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник региональных целевых статей (только для организаций) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_CSR_USER_2016_1]

AS

SELECT max(LINK) as Link, 0 as Link_Self,K.Code as [CODE],O.Link_Org as [ORG],O.Link_Budg as [BUDG],max(coalesce(O.Long_Name, O.Name, K.Long_name, K.name)) as [NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] K JOIN dbo.REPORT_KBK_ORG O on K.Link = O.Link_KBK WHERE Code_Form = 'ЦСР_2016_USER' GROUP BY K.Code,O.Link_Org,O.Link_Budg,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_CSR_USER_2016_1] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_USER_2016_1')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_USER_2016_1'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_1', 'Справочник региональных целевых статей (только для организаций)', 223, (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_CSR_USER_2016_1', NAME = 'Справочник региональных целевых статей (только для организаций)', ORDERS = '223', 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_CSR_USER_2016_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_1_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_1_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_1_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_1_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_1_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_1_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_1_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_1_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_1_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1_Org')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_1_Org', '', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_1_Org', NAME = '', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_1_Org'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1_Budg')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_1_Budg', '', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_1_Budg', NAME = '', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_1_Budg'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1', 'TITLE', 'Справочник региональных целевых статей (только для организаций)'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_CSR_USER_2016_1'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_CSR_USER_2016_1'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1', 'SERVER_TABLE_NAME', 'R_SPR_CSR_USER_2016_1'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_CSR_USER_2016_1'''
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_Org', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_Org', 'CONTROLSOURCE', 'm.cAlias + ".Org"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_Org', 'FIELD_DATA', 'Org'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_Budg', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_Budg', 'CONTROLSOURCE', 'm.cAlias + ".Budg"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_1_Budg', 'FIELD_DATA', 'Budg'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2016_1', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2016_1', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2016_1', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2016_1', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник целевых статей (для организаций) С КОДОМ R_SPR_CSR_USER_2016------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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', 3, 'name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Org', 4, 'Org', '', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Budg', 5, 'Budg', '', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_CSR_USER_2016_1', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_CSR_USER_2016_2', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_CSR_USER_2016'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_CSR_USER_2016', 'Справочник целевых статей (для организаций)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник целевых статей (для организаций) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_CSR_USER_2016]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Org as [ORG],Budg as [BUDG],max(name) as [NAME],begin_date,end_date FROM R_SPR_CSR_USER_2016_1 GROUP BY Code,Org,Budg,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Org as [ORG],Budg as [BUDG],max(name) as [NAME],begin_date,end_date FROM R_SPR_CSR_USER_2016_2 GROUP BY Code,Org,Budg,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_CSR_USER_2016] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_USER_2016')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_USER_2016'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016', 'Справочник целевых статей (для организаций)', 226, (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_CSR_USER_2016', NAME = 'Справочник целевых статей (для организаций)', ORDERS = '226', 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_CSR_USER_2016'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_Org')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_Org', '', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_Org', NAME = '', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_Org'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016_Budg')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2016_Budg', '', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2016_Budg', NAME = '', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2016_Budg'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016', 'TITLE', 'Справочник целевых статей (для организаций)'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_CSR_USER_2016'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_CSR_USER_2016'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016', 'SERVER_TABLE_NAME', 'R_SPR_CSR_USER_2016'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_CSR_USER_2016'''
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_Org', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_Org', 'CONTROLSOURCE', 'm.cAlias + ".Org"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_Org', 'FIELD_DATA', 'Org'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_Budg', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_Budg', 'CONTROLSOURCE', 'm.cAlias + ".Budg"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2016_Budg', 'FIELD_DATA', 'Budg'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2016', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2016', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2016', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2016', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Автозаполняемый справочник для формы 0503117G - Расходы С КОДОМ R_SPR_RASH_117_2016------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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 ('Code_str', 2, 'Code_str', 'Код строки', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 3, 'isnull(Long_Name,Name)', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_RASH_117_2016'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_RASH_117_2016', 'Автозаполняемый справочник для формы 0503117G - Расходы', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Автозаполняемый справочник для формы 0503117G - Расходы (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_RASH_117_2016]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Code_str as [CODE_STR],max(isnull(Long_Name,Name)) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_RASH_117_2016' GROUP BY Code,Code_str, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_RASH_117_2016] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_RASH_117_2016')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_RASH_117_2016'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_117_2016', 'Автозаполняемый справочник для формы 0503117G - Расходы', 221, (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_RASH_117_2016', NAME = 'Автозаполняемый справочник для формы 0503117G - Расходы', ORDERS = '221', 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_RASH_117_2016'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_117_2016_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_117_2016_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_117_2016_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_117_2016_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_117_2016_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_117_2016_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_117_2016_Code_str', 'Код строки', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_117_2016_Code_str', NAME = 'Код строки', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_117_2016_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_117_2016_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_117_2016_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_117_2016_Name'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016', 'TITLE', 'Автозаполняемый справочник для формы 0503117G - Расходы'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_RASH_117_2016'')'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_RASH_117_2016'')'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016', 'SERVER_TABLE_NAME', 'R_SPR_RASH_117_2016'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_RASH_117_2016'''
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_Code_str', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2016_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_117_2016', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_117_2016', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_117_2016', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_117_2016', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_RASH_117_2016',0,'Автозаполняемый справочник для формы 0503117G - Расходы','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_RASH_117_2016',@link_self,'Автозаполняемый справочник для формы 0503117G - Расходы','HEADER'
GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'01011234567891021',@link_self,'','R_SPR_RASH_117_2016',0,'200',0,'','Субсидии на обеспечение жильем молодых семей и молодых специалистов, проживающих и работающих в сельской местности','19000101','30000101'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, '', 'Субсидии на обеспечение жильем молодых семей и молодых специалистов, проживающих и работающих в сельской местности', '19000101'


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'79000000000000000',@link_self,'','R_SPR_RASH_117_2016',0,'450',0,'','Результат исполнения бюджета (дефицит / профицит)','19000101','30000101'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, '', 'Результат исполнения бюджета (дефицит / профицит)', '19000101'


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'96000000000000000',@link_self,'','R_SPR_RASH_117_2016',0,'200',0,'','Итого','19000101','30000101'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, '', 'Итого', '19000101'


GO

GO

------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник ВР (для организаций) С КОДОМ R_SPR_VR_USER_2011------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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', 3, 'name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Org', 4, 'Org', '', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Budg', 5, 'Budg', '', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('code_str', 6, '''200''', 'Код строки', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_VR_USER_2011_1', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_VR_USER_2011_2', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_VR_USER_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_VR_USER_2011', 'Справочник ВР (для организаций)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник ВР (для организаций) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_VR_USER_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Org as [ORG],Budg as [BUDG],'200' as [CODE_STR],max(name) as [NAME],begin_date,end_date FROM R_SPR_VR_USER_2011_1 GROUP BY Code,Org,Budg,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Org as [ORG],Budg as [BUDG],'200' as [CODE_STR],max(name) as [NAME],begin_date,end_date FROM R_SPR_VR_USER_2011_2 GROUP BY Code,Org,Budg,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_VR_USER_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_VR_USER_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_VR_USER_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011', 'Справочник ВР (для организаций)', 228, (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_VR_USER_2011', NAME = 'Справочник ВР (для организаций)', ORDERS = '228', 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_VR_USER_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_Org')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_Org', '', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_Org', NAME = '', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_Org'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_Budg')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_Budg', '', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_Budg', NAME = '', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_Budg'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_code_str', 'Код строки', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_code_str', NAME = 'Код строки', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_code_str'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011', 'TITLE', 'Справочник ВР (для организаций)'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_VR_USER_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_VR_USER_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011', 'SERVER_TABLE_NAME', 'R_SPR_VR_USER_2011'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_VR_USER_2011'''
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_Org', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_Org', 'CONTROLSOURCE', 'm.cAlias + ".Org"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_Org', 'FIELD_DATA', 'Org'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_Budg', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_Budg', 'CONTROLSOURCE', 'm.cAlias + ".Budg"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_Budg', 'FIELD_DATA', 'Budg'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_code_str', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_code_str', 'CONTROLSOURCE', 'm.cAlias + ".code_str"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_code_str', 'FIELD_DATA', 'code_str'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_USER_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_USER_2011', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_USER_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_USER_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
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,
		@iKbkLen int

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 

if @liYear < 2016
	set @iKbkLen = 17
else
	set @iKbkLen = 20

--- Выборка счетов для расчета остатков ---
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,'.','')),'') + '00000000000000000000', @iKbkLen)
			+ 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,'.','')),'') + '00000000000000000000', @iKbkLen)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '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', @iKbkLen)
			+ 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', @iKbkLen)
			+ 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', @iKbkLen)
			+ 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', @iKbkLen)
			+ 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', @iKbkLen)
			+ 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', @iKbkLen)
			+ 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

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

GO

/*

	c Кейсистемс (Keysystems), 2010
	Печать форм 127 (для параметра "все атрибуты в один отчет)
	Печать с подитогами
*/


CREATE       PROCEDURE dbo.RO_PRINT_127_ITOG_16
	@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

declare @varKSiParam int, -- 0 - без подитогов, 1 бит - подитоги по ЭКР, 2 бит - подитоги по ВР, 3 бит - подитоги по ЦСР, 4 бит - подитоги по подразделу, 5 бит - подитоги по раздеру, 6 бит - подитоги по администратору
		@varKSiNoItog int, @iYear INT, @vcAtr VARCHAR(50), @varKSiRashEKR TINYINT, @varKSiNoItogRash TINYINT

SET @vcAtr = dbo.RN_GET_ATR_VALUE(@LSF, 'REPORTS_ATR_ADM')

set @varKSiParam = 0
set @varKSiNoItog = 0
SET @varKSiRashEKR = 3
SET @varKSiNoItogRash = 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'
select @varKSiRashEKR = convert(int, Value) from #Param_Print where Param = 'RASH_EKR'
select @varKSiNoItogRash = convert(int, Value) from #Param_Print where Param = 'NoItog_Rash'
END


if isnull(@varKSiNoItog,0) = 1
begin
	exec dbo.RO_PRINT_NO_ITOG @LSF, @bDeleteEmptyRows, @data, @notNullCol, @AtrInOnePage, @WEB_excel
	return
end


IF @LSF is NULL
	return -1

declare @iLF int, @iLT INT, @dBeginDate DATETIME
select @iLF = Link_Form, @iYear = YEAR(begin_date), @dBeginDate = Begin_Date
from report_saved_forms where Link_Saved_Form = @LSF

if isnull(@WEB_excel, 0) <> 1
	select '' col1

-- таблица доходы
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(1500), Col2 varchar(1000), Col3 varchar(1000),  Col4 float, Col5 float, Col6 float, Col7 float, Col8 float, Col9 float)

insert #doh (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9)
exec dbo.rn_get_all_adm_table 	@LSF, 1, @bDeleteEmptyRows, @AtrInOnePage, 1

IF NOT EXISTS(SELECT * FROM #doh)
BEGIN
insert #doh (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9)
SELECT 0, 0, 0, @LSF, 0, -1, 0, 0, '00085000000000000000', 'Доходы - всего', '010', '85000000000000000', 0, 0, 0, 0, 0, 0
END

SELECT * FROM #doh


------------------------------------------------------------------------------------------------
--- ТАБЛИЦА РАСХОДЫ С ПОДИТОГАМИ
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(1500), Col2 varchar(1000), Col3 varchar(1000), Col4 varchar(1000), Col5 varchar(1000), Col6 float, Col7 float, Col8 float, Col9 float, Col10 float, Col11 float, Col12 float, Col13 float, Col14 varchar(50))

select * into #rash_itog from #rash

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)
exec dbo.rn_get_all_adm_table 	@LSF, 2, @bDeleteEmptyRows, @AtrInOnePage, 1



IF @varKSiRashEKR = 1
BEGIN
UPDATE #rash
SET COL6 = 0,
COL7 = 0,
COL12 = 0,
COL13 = 0
WHERE RIGHT(RTRIM(CODE),3) <> '000'
END

IF @varKSiRashEKR = 2
BEGIN
UPDATE #rash
SET COL6 = 0,
COL7 = 0,
COL12 = 0,
COL13 = 0
WHERE RIGHT(RTRIM(CODE),2) <> '00'
END

IF @varKSiNoItogRash = 1
BEGIN
DELETE #rash
WHERE RIGHT(RTRIM(CODE),3) IN ('200', '210', '220', '230', '240', '250', '260', '300', '500', '600')

IF @varKSiParam = 0
BEGIN
DELETE #rash
WHERE RIGHT(RTRIM(CODE),3) IN ('000') AND LEFT(code,7) NOT IN ('0009600', '0007900')
END

END

---------------------------------------------
/*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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,14) + '000000', '', max(Col2),max(Col3), max(Col4), '000',sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), left(Col14,14) + '000000'
	from #rash
	where col5 <> '000'
	group by left(Code,14) + '000000', left(Col14,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,7) + '0000000000000', '', max(Col2),max(Col3), '0000000', '000', sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), left(col14,7) + '0000000000000'
	from #rash
	where col5 <> '000'
	group by left(Code,7) + '0000000000000', left(col14,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,5) + '000000000000000', '', max(Col2),left(col3,2) + '00', '0000000', '000', sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), left(col14,5) + '000000000000000'
	from #rash
	where col5 <> '000'
	group by left(Code,5) + '000000000000000', left(Col14,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,3) + '00000000000000000', '', max(Col2),'000', '0000000', '000', sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13),  left(col14,3) + '00000000000000000'
	from #rash
	where  col5 <> '000'
	group by left(Code,3) + '00000000000000000', left(Col14,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,12) + '00000000', '', max(Col2),max(Col3), max(Col4), '000', sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), left(Col14,12) + '00000000'
	from #rash
	where  col5 <> '000'
	group by left(Code,12) + '00000000', left(Col14,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,10) + '0000000000', '', max(Col2),max(Col3), max(Col4), '000', sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), left(Col14,10) + '0000000000'
	from #rash
	where col5 <> '000'
	group by left(Code,10) + '0000000000', left(Col14,10) + '0000000000'
END

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)
SELECT 0,0,0,@LSF, 0, -1, 0, 0, '00096000000000000000', 'Расходы - всего', '', '', '', '', 0,0,0,0,0,0,0,0, '00096000000000000000'
WHERE NOT EXISTS(SELECT * FROM #rash WHERE code LIKE '%96000000000000%')

-- убираем целевые которых нет в справочнике
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
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)

UPDATE #rash
SET COL1 = ''
WHERE  col5 <> '000'

if @iYear < 2011
exec ro_get_name_spr @iLT, 'COL5=SUBSTRING(CODE,15,3)=000#COL4=SUBSTRING(CODE,5,10)=0000000#COL3=SUBSTRING(CODE,1,4)=0000#RN_VIEW_KBK_ADM_M=LEFT(CODE,4)=000', '#rash', @varKScNameCode = 'CODE', @varKScNameName = 'COL1', @varKSiLSF = @LSF
else
exec ro_get_name_spr @iLT, 'COL5=SUBSTRING(CODE,15,3)=000#COL4=SUBSTRING(CODE,5,10)=0000000#COL3=SUBSTRING(CODE,1,4)=0000#R_SPR_ADM_2011=LEFT(CODE,4)=000', '#rash', @varKScNameCode = 'CODE', @varKScNameName = 'COL1', @varKSiLSF = @LSF
----------------------------------------------

--if @AtrInOnePage = 1 -- еще общий итог по администраторма
--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)
--	select 0, 0, 0, max(link_saved_form), 0, -1, 0, 0, '00096000000000000000', 'Расходы - всего', max(Col2),'000', '9600000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), '00096000000000000000'
--	from #rash
--	where col6 = '000' and col5 <> '000'
--end

select * from #rash order by left(code, 3), orders, Code

drop table #rash_itog
drop table #rash
-------------------------------------------------------------------------------------------------

-- таблица источники
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(1000), Col2 varchar(1000), Col3 varchar(1000), Col4 float, Col5 float, Col6 float, Col7 float, Col8 float, Col9 float, Col10 varchar(50))

insert #ist exec dbo.rn_get_all_adm_table 	@LSF, 3, @bDeleteEmptyRows, @AtrInOnePage, 1

-- добавляем обязательные кода:
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)
select 0, 0, 0, 0, 0, -2, 0, 0, '00050090000000000000000', 'Источники финансирования дефицита бюджета - всего', '500', '90000000000000000', 0,0,0,0,0,0,'00050090000000000000000'
where not exists (select top 1 * from #ist where code =  '00050090000000000000000')

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)
select 0, 0, 0, 0, 0, -1, 0, 0, '00052001000000000000000', 'источники внутреннего финансирования бюджета', '520', '01000000000000000', 0,0,0,0,0,0,'00052001000000000000000'
where not exists (select top 1 * from #ist where code =  '00052001000000000000000')

update #ist
set orders = 2
where col2 = '620'

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)
select 0, 0, 0, 0, 0, 1, 0, 0, '00062002000000000000000', 'источники внешнего финансирования бюджета', '620', '02000000000000000', 0,0,0,0,0,0,'00062002000000000000000'
where not exists (select top 1 * from #ist where code =  '00062002000000000000000')

update #ist
set orders = 3
where col2 like '7%'

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)
select 0, 0, 0, 0, 0, 3, 0, 0, CASE WHEN @AtrInOnePage = 1 THEN '000' ELSE RTRIM(@vcAtr) END  + '70001050000000000000', 'Изменение остатков средств', '700', '', 0,0,0,0,0,0,'00070001050000000000000'
where not exists (select top 1 * from #ist where substring(code,4, 20) =  '70001050000000000000')

update #ist
set orders = 5
where col2 = '710'

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)
select 0, 0, 0, 0, 0, 4, 0, 0, CASE WHEN @AtrInOnePage = 1 THEN '000' ELSE RTRIM(@vcAtr) END  + '71001050000000000500', 'увеличение остатков средств, всего', '710', '', 0,0,0,0,0,0,'00071001050000000000500'
where not exists (select top 1 * from #ist where substring(code,4, 20) =  '71001050000000000500')

update #ist
set orders = 7
where col2 = '720'

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)
select 0, 0, 0, 0, 0, 6, 0, 0, CASE WHEN @AtrInOnePage = 1 THEN '000' ELSE RTRIM(@vcAtr) END  + '72001050000000000600', 'уменьшение остатков средств, всего', '720', '', 0,0,0,0,0,0,'00072001050000000000600'
where not exists (select top 1 * from #ist where substring(code,4, 20) =  '72001050000000000600')

update #ist
set orders = 8
where col2 like '8%'

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00080004000000000000000', 'Изменение остатков по расчетам (стр.810 + 820)', '800', '04000000000000000', 0,0,0,0,0,0,'00080004000000000000000'
where not exists (select top 1 * from #ist where code =  '00080004000000000000000')

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00081005000000000000000', 'изменение остатков по расчетам с органами, организующими исполнение бюджета (стр.811 + 812)', '810', '05000000000000000', 0,0,0,0,0,0,'00081005000000000000000'
where not exists (select top 1 * from #ist where code =  '00081005000000000000000')

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00081106000000000000000', 'увеличение счетов расчетов (дебетовый остаток счета 121002000)', '811', '06000000000000000', 0,0,0,0,0,0,'00081106000000000000000'
where not exists (select top 1 * from #ist where code =  '00081106000000000000000')

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00081207000000000000000', 'уменьшение счетов расчетов (кредитовый остаток счета 130405000)', '812', '07000000000000000', 0,0,0,0,0,0,'00081207000000000000000'
where not exists (select top 1 * from #ist where code =  '00081207000000000000000')

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00082008000000000000000', 'Изменение остатков по внутренним расчетам (стр.821 + стр. 822)', '820', '08000000000000000', 0,0,0,0,0,0,'00082008000000000000000'
where not exists (select top 1 * from #ist where code =  '00082008000000000000000')

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00082109000000000000000', 'увеличение остатков по внутренним расчетам', '821', '09000000000000000', 0,0,0,0,0,0,'0082109000000000000000'
where not exists (select top 1 * from #ist where code =  '00082109000000000000000')

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00082201000000000000000', 'уменьшение остатков по внутренним расчетам', '822', '01000000000000000', 0,0,0,0,0,0,'00082201000000000000000'
where not exists (select top 1 * from #ist where code =  '00082201000000000000000')

select * from #ist order by orders, col2, code

drop table #ist

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.[RO_PRINT_127_ITOG_16] TO PUBLIC

GO



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 = '0503127M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = ',REPORTS_ATR_VIDDEYAT=1,,REPORTS_ATR_PRP=500'


	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 = '0503127M' AND RF.START_DATE = '20160101' and RCF.[ORDER] = 0 and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = ',REPORTS_ATR_VIDDEYAT=1,,REPORTS_ATR_PRP=500'

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, 1,0,''
	from dbo.REPORT_FORMS where CODE = '0503127M' AND [START_DATE] = '20160101' 
	SET @iCalcFormLink = @@IDENTITY
	
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_ADM', '000', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_PRP', '500', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_ATR_VIDDEYAT', '1', NULL)
INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, 'REPORTS_FILTER_KBK', 'Не отобрано', NULL)
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 4
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.503.15','','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,2,'1.503.14','','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,1,'1.503.11','','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 2,2,'','1.503.15','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 3,1,'','1.503.14','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 4,2,'','1.503.11','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 6
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,3,'1.304.05','1.304.04','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,1,'','1.304.05','','211,212,213,221,222,223,224,225,226,231,232,241,242,251,252,253,261,262,263,290,310,320,330,340,530',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 1,3,'1.304.04','1.304.05','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 1,2,'1.304.05','','211,212,213,221,222,223,224,225,226,231,232,241,242,251,252,253,261,262,263,290,310,320,330,340,530','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 5
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.501.15','','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,2,'1.501.14','','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,1,'1.501.11','','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 2,2,'','1.501.15','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 3,1,'','1.501.14','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 4,2,'','1.501.11','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 7
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '2'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.201.2[17]','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 2,3,'1.304.04','1.201.2[17]','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 3,2,'1.201.2[17]','','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 3,3,'1.201.2[17]','1.304.04','','',1,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 4
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.503.11','','','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,1,'1.503.15','','','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,2,'1.503.14','','','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,1,'1.503.11','','','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,1,'1.503.15','','','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,2,'1.503.14','','','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 2,2,'','1.503.15','','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 2,2,'','1.503.15','','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 3,1,'','1.503.14','','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 3,1,'','1.503.14','','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 4,2,'','1.503.11','','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 4,2,'','1.503.11','','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 5
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.210.02','','171,410,620,630,640,650,710,720','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,1,'1.304.05','','310,520,540,550,810,820','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,1,'1.304.05','','310,520,540,550,810,820','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,3,'1.304.05','1.304.04','','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,2,'','1.210.02','','171,410,620,630,640,650,710,720',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 1,3,'1.304.05','1.304.04','','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,2,'','1.210.02','','171,410,620,630,640,650,710,720',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,3,'1.304.05','1.304.04','','',0,1,'81207#000000000000000',1,''
	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, 1,2,'1.304.05','','','',0,1,'81207#000000000000000',0,''
	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, 1,2,'','1.304.05','','310,520,540,550,810,820',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 1,3,'1.304.04','1.304.05','','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 1,1,'1.210.02','','171,410,620,630,640,650,710,720','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,2,'1.210.02','','','',0,3,'81106#000000000000000',0,''
	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, 1,1,'','1.304.05','','',0,1,'81207#000000000000000',1,''
	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, 1,3,'1.304.04','1.304.05','','',0,1,'81207#000000000000000',1,''
	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, 1,2,'','1.304.05','','310,520,540,550,810,820',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 1,3,'1.304.04','1.304.05','','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 6
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.201.2[137]','','','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,1,'1.201.2[137]','','','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,2,'','1.201.2[137]','','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 1,2,'','1.201.2[137]','','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 2,2,'1.201.2[1237]','','510','',15,1,'710#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 2,1,'','1.201.2[137]','','610',15,1,'720#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 2,1,'1.201.2[1237]','1.304.04','510','',0,1,'82109#000000000000000',0,''
	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, 2,2,'1.304.04','1.201.2[137]','','610',0,1,'82201#000000000000000',1,''
	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, 2,1,'1.304.05','1.304.04','510','',0,1,'82109#000000000000000',0,''
	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, 2,2,'1.304.04','1.304.05','','',0,1,'82201#000000000000000',1,''
	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, 3,2,'1.304.05','1.304.04','','',0,1,'81207#000000000000000',0,''
	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, 3,1,'1.304.04','1.304.05','','',0,1,'81207#000000000000000',1,''
	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, 4,3,'1.201.2[137]','1.304.04','','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 4,3,'1.304.04','1.201.2[137]','','',8,1,'620#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
	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, 4,3,'1.201.2[137]','1.304.04','','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 4,3,'1.304.04','1.201.2[137]','','',4,1,'520#dddxxxxxxxxxxxxxxxxxddddddddd',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 5
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.210.02','','110,120,130,140,151,152,153,160,180,410,420,430,440','',2,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,2,'','1.210.02','','110,120,130,140,151,152,153,160,180,410,420,430,440',2,1,'dddxxxxxxxxxxxxxxxxxddddddddd',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',0,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 6
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.201.2[137]','','110,120,130,140,151,152,153,160,180,410,420,430,440','',2,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
	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, 1,2,'','1.201.2[137]','','110,120,130,140,151,152,153,160,180,410,420,430,440',2,1,'dddxxxxxxxxxxxxxxxxxddddddddd',1,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 7
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '3'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'','1.304.04','','',0,1,'82109#000000000000000',1,''
	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, 1,2,'1.304.04','','','',0,1,'82209#000000000000000',0,''
set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, '',1,0,''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = 4
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = '1'
			
			SET @iCalcLink = @@IDENTITY
		
	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, 1,1,'1.507.10','1.504.10','','',2,1,'dddxxxxxxxxxxxxxxxxxddddddddd',0,''
GO
EXEC [dbo].[RO_KBK_CASHE_UPDATE]
GO
exec RN_SAVE_REPORT_KBK 0,'ЦСР_2016',0,'Целевые статьи','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='SHARED_2011' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'ЦСР_2016',@link_self,'Целевые статьи','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'ЦСР_2016')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'ЦСР_2016')
delete report_kbk where code_form= 'ЦСР_2016'
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 '0100000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие здравоохранения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0110000000',0,'ЦСР_2016',1,'Подпрограмма "Профилактика заболеваний и формирование здорового образа жизни. Развитие первичной медико-санитарной помощи"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0110100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие системы медицинской профилактики неинфекционных заболеваний и формирования здорового образа жизни"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0110200000',0,'ЦСР_2016',1,'Основное мероприятие "Профилактика инфекционных заболеваний, включая иммунопрофилактику"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0110300000',0,'ЦСР_2016',1,'Основное мероприятие "Профилактика ВИЧ, вирусных гепатитов В и С"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0110351790',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на реализацию мероприятий по профилактике ВИЧ-инфекции и гепатитов B и C',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0110400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие первичной медико-санитарной помощи, а также системы раннего выявления заболеваний, патологических состояний и факторов риска их развития, включая проведение медицинских осмотров и диспансеризации населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0110500000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование механизмов обеспечения населения лекарственными препаратами, медицинскими изделиями, специализированными продуктами лечебного питания для детей-инвалидов в амбулаторных условиях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0110551330',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на осуществление организационных мероприятий по обеспечению лиц лекарственными препаратами, предназначенными для лечения больных злокачественными новообразованиями лимфоидной, кроветворной и родственных им тканей, гемофил',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0110551610',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на реализацию отдельных полномочий в области лекарственного обеспечения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0110600000',0,'ЦСР_2016',1,'Основное мероприятие "Первичная профилактика стоматологических заболеваний среди населения Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0110700000',0,'ЦСР_2016',1,'Основное мероприятие "Диспансерное наблюдение больных с артериальной гипертонией"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120000000',0,'ЦСР_2016',1,'Подпрограмма "Совершенствование оказания специализированной, включая высокотехнологичную, медицинской помощи"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы оказания медицинской помощи больным туберкулезом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120151740',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на финансовое обеспечение закупок антибактериальных и противотуберкулезных лекарственных препаратов (второго ряда), применяемых при лечении больных туберкулезом с множественной лекарственной устойчивостью возбудителя, и д',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120200000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование оказания медицинской помощи лицам, инфицированным вирусом иммунодефицита человека, гепатитами В и С"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120250720',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на финансовое обеспечение закупок антивирусных препаратов для профилактики и лечения лиц, инфицированных вирусами иммунодефицита человека и гепатитов B и C',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120300000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы оказания медицинской помощи наркологическим больным"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120400000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы оказания медицинской помощи больным с психическими расстройствами и расстройствами поведения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120500000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы оказания медицинской помощи больным сосудистыми заболеваниями"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120600000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы оказания медицинской помощи больным онкологическими заболеваниями"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120700000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие системы донорства органов человека в целях трансплантации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120754920',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на обеспечение медицинской деятельности, связанной с донорством органов человека в целях трансплантации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120800000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование оказания медицинской помощи пострадавшим при дорожно-транспортных происшествиях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120900000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы оказания медицинской помощи больным прочими заболеваниями"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120953820',0,'ЦСР_2016',1,'Субсидии на реализацию отдельных мероприятий государственной программы Российской Федерации "Развитие здравоохранения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0120960210',0,'ЦСР_2016',1,'Субсидии на возмещение затрат, связанных с осуществлением деятельности, направленной на решение социальных вопросов, защиту прав и законных интересов граждан',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0121000000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование высокотехнологичной медицинской помощи"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0121054010',0,'ЦСР_2016',1,'Финансовое обеспечение оказания высокотехнологичной медицинской помощи, не включенной в базовую программу обязательного медицинского страхования',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0121054020',0,'ЦСР_2016',1,'Софинансирование расходов, возникающих при оказании гражданам Российской Федерации высокотехнологичной медицинской помощи, не включенной в базовую программу обязательного медицинского страхования',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0121100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие службы крови"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0130000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие и внедрение инновационных методов диагностики, профилактики и лечения, а также основ персонализированной медицины"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0130100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие ядерной медицины"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0130200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие фундаментальной, трансляционной и персонализированной медицины"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0130300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие инновационной инфраструктуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0130400000',0,'ЦСР_2016',1,'Основное мероприятие "Медицинская помощь, оказываемая в рамках клинической апробации методов профилактики, диагностики, лечения и реабилитации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0140000000',0,'ЦСР_2016',1,'Подпрограмма "Охрана здоровья матери и ребенка"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0140100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование службы родовспоможения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0140139640',0,'ЦСР_2016',1,'Оплата медицинской помощи женщинам в период беременности, родов и в послеродовом периоде, а также профилактического медицинского осмотра ребенка в течение первого года жизни',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0140200000',0,'ЦСР_2016',1,'Основное мероприятие "Создание системы раннего выявления и коррекции нарушений развития ребёнка"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0140300000',0,'ЦСР_2016',1,'Основное мероприятие "Выхаживание детей с экстремально низкой массой тела"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0140400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие специализированной медицинской помощи детям"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0140500000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование методов борьбы с вертикальной передачей ВИЧ от матери к плоду"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0140600000',0,'ЦСР_2016',1,'Основное мероприятие "Профилактика абортов.  Развитие центров медико-социальной поддержки беременных, оказавшихся в трудной жизненной ситуации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0150000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие медицинской реабилитации и санаторно-курортного лечения, в том числе детей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0150100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие санаторно-курортного лечения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0150200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие медицинской реабилитации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0160000000',0,'ЦСР_2016',1,'Подпрограмма "Оказание паллиативной помощи, в том числе детям"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0160100000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание паллиативной помощи взрослым"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0160200000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание паллиативной помощи детям"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0170000000',0,'ЦСР_2016',1,'Подпрограмма "Кадровое обеспечение системы здравоохранения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0170100000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение квалификации и переподготовка медицинских и фармацевтических работников"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0170200000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение престижа медицинских специальностей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0170300000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка отдельных категорий медицинских работников"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0170351360',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на осуществление единовременных выплат медицинским работникам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0170400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие сети обучающих симуляционных центров"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0170500000',0,'ЦСР_2016',1,'Основное мероприятие "Внедрение профессиональных стандартов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0180000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие международных отношений в сфере охраны здоровья"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0180100000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование национальной системы содействия международному развитию в сфере охраны здоровья"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0180200000',0,'ЦСР_2016',1,'Основное мероприятие "Исполнение международных обязательств Российской Федерации в сфере охраны здоровья"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0190000000',0,'ЦСР_2016',1,'Подпрограмма "Экспертиза и контрольно-надзорные функции в сфере охраны здоровья"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0190100000',0,'ЦСР_2016',1,'Основное мероприятие "Контроль качества и безопасности медицинской деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0190200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственный контроль в сфере обращения лекарственных средств"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0190300000',0,'ЦСР_2016',1,'Основное мероприятие "Государственный контроль за обращением медицинских изделий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0190400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие государственной судебно-медицинской экспертной деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0190500000',0,'ЦСР_2016',1,'Основное мероприятие "Государственный санитарно-эпидемиологический надзор"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0190600000',0,'ЦСР_2016',1,'Основное мероприятие "Организация обеспечения санитарно-эпидемиологического благополучия населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0190700000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

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Б0000000',0,'ЦСР_2016',1,'Подпрограмма "Медико-санитарное обеспечение отдельных категорий граждан"',0,'',0,'','', '19000101',NULL,0

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Б0100000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание медицинской помощи работникам отдельных отраслей экономики с особо опасными условиями труда и населению отдельных территорий с опасными для здоровья человека физическими, химическими и биологическими факторами"',0,'',0,'','', '19000101',NULL,0

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Б0151970',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на реализацию отдельных полномочий в области лекарственного обеспечения населения закрытых административно-территориальных образований, обслуживаемых федеральными государственными бюджетными учреждениями здравоохранения,',0,'',0,'','', '19000101',NULL,0

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Б0200000',0,'ЦСР_2016',1,'Основное мероприятие "Медицинское и медико-биологическое  обеспечение спортсменов сборных команд Российской Федерации"',0,'',0,'','', '19000101',NULL,0

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Б0300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие и внедрение инновационных технологий в сфере защиты отдельных категорий граждан от воздействия особо опасных факторов физической, химической и биологической природы, а также обеспечение безопасности пилотируемых космиче',0,'',0,'','', '19000101',NULL,0

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Г0000000',0,'ЦСР_2016',1,'Подпрограмма "Управление развитием отрасли"',0,'',0,'','', '19000101',NULL,0

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Г0100000',0,'ЦСР_2016',1,'Основное мероприятие "Информационно-аналитическая поддержка реализации государственной программы"',0,'',0,'','', '19000101',NULL,0

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Г0200000',0,'ЦСР_2016',1,'Основное мероприятие "Информатизация здравоохранения, включая развитие телемедицины"',0,'',0,'','', '19000101',NULL,0

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Г0300000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация функций аппаратов исполнителей и участников государственной программы"',0,'',0,'','', '19000101',NULL,0

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Г0400000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование статистического наблюдения в сфере здравоохранения"',0,'',0,'','', '19000101',NULL,0

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Д0000000',0,'ЦСР_2016',1,'Подпрограмма "Организация обязательного медицинского страхования граждан Российской Федерации"',0,'',0,'','', '19000101',NULL,0

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Д0100000',0,'ЦСР_2016',1,'Основное мероприятие "Финансовое обеспечение территориальных программ обязательного медицинского страхования в рамках базовой программы обязательного медицинского страхования"',0,'',0,'','', '19000101',NULL,0

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Д0150930',0,'ЦСР_2016',1,'Субвенции бюджетам территориальных фондов обязательного медицинского страхования на финансовое обеспечение организации обязательного медицинского страхования на территориях субъектов Российской Федерации',0,'',0,'','', '19000101',NULL,0

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Д0155060',0,'ЦСР_2016',1,'Иные межбюджетные трансферты бюджетам территориальных фондов обязательного медицинского страхования на дополнительное финансовое обеспечение оказания специализированной, в том числе высокотехнологичной, медицинской помощи, включенной в базовую програ',0,'',0,'','', '19000101',NULL,0

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Д0200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение застрахованных лиц полисами обязательного медицинского страхования единого образца"',0,'',0,'','', '19000101',NULL,0

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Д0300000',0,'ЦСР_2016',1,'Основное мероприятие "Управление средствами нормированного страхового запаса Федерального фонда обязательного медицинского страхования"',0,'',0,'','', '19000101',NULL,0

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Д0400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение компенсации выпадающих доходов системы обязательного медицинского страхования в связи с установлением пониженных тарифов страховых взносов"',0,'',0,'','', '19000101',NULL,0

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Д0451820',0,'ЦСР_2016',1,'Иной межбюджетный трансферт на компенсацию выпадающих доходов бюджета Федерального фонда обязательного медицинского страхования в связи с установлением пониженных тарифов страховых взносов',0,'',0,'','', '19000101',NULL,0

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И0000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие скорой медицинской помощи"',0,'',0,'','', '19000101',NULL,0

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И0100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование оказания скорой, в том числе скорой специализированной, медицинской помощи, медицинской эвакуации"',0,'',0,'','', '19000101',NULL,0

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И0200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие системы оказания медицинской помощи в неотложной и экстренной формах"',0,'',0,'','', '19000101',NULL,0

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И0300000',0,'ЦСР_2016',1,'Основное мероприятие "Информатизация системы оказания медицинской помощи в неотложной и экстренной формах"',0,'',0,'','', '19000101',NULL,0

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И0400000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование деятельности Всероссийской службы медицины катастроф"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0200000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие образования" на 2013 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210000000',0,'ЦСР_2016',1,'Подпрограмма "Реализация образовательных программ профессионального образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210100000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация образовательных программ в вузах"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210162350',0,'ЦСР_2016',1,'Субсидии негосударственным образовательным организациям, имеющим аккредитацию, на оказание государственных услуг по реализации образовательных программ среднего профессионального образования и образовательных программ высшего образования',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210200000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация образовательных программ среднего профессионального образования и профессионального обучения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210260210',0,'ЦСР_2016',1,'Субсидии на возмещение затрат, связанных с осуществлением деятельности, направленной на решение социальных вопросов, защиту прав и законных интересов граждан',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210300000',0,'ЦСР_2016',1,'Основное мероприятие "Социальная поддержка работников организаций профессионального образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210400000',0,'ЦСР_2016',1,'Основное мероприятие "Социальная поддержка обучающихся в организациях профессионального образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210464810',0,'ЦСР_2016',1,'Субсидии на возмещение части затрат на уплату процентов по образовательным кредитам, предоставляемым студентам образовательных организаций высшего образования',0,'',0,'','', '19000101',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 '0210500000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка талантливой молодежи в организациях профессионального образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210530490',0,'ЦСР_2016',1,'Премии Правительства Российской Федерации в области образования',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210560540',0,'ЦСР_2016',1,'Субсидии Фонду "Талант и успех", г. Сочи, Краснодарский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210600000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие инфраструктуры системы профессионального образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210700000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка программ развития вузов и приоритетных образовательных программ"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0210800000',0,'ЦСР_2016',1,'Ведомственная целевая программа "Повышение квалификации инженерно-технических кадров на 2015 - 2016 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0220000000',0,'ЦСР_2016',1,'Подпрограмма "Содействие развитию дошкольного и общего образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0220100000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие развитию дошкольного образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0220200000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие развитию общего образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0220300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие кадрового потенциала системы дошкольного и общего образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0220350880',0,'ЦСР_2016',1,'Субсидии на поощрение лучших учителей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0220400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие инфраструктуры системы дошкольного и общего образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0220450970',0,'ЦСР_2016',1,'Субсидии на создание в общеобразовательных организациях, расположенных в сельской местности, условий для занятий физической культурой и спортом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие дополнительного образования детей и реализация мероприятий молодежной политики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240100000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация образовательных программ дополнительного образования детей и мероприятия по их развитию"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240200000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие развитию дополнительного образования и социализации детей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240260070',0,'ЦСР_2016',1,'Субсидии организациям, осуществляющим мероприятия по содействию развитию дополнительного образования детей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240262270',0,'ЦСР_2016',1,'Субсидии Общероссийской общественно-государственной организации "Добровольное общество содействия армии, авиации и флоту России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240300000',0,'ЦСР_2016',1,'Основное мероприятие "Выявление и поддержка одаренных детей и молодежи"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240330380',0,'ЦСР_2016',1,'Премии Президента Российской Федерации для поддержки талантливой молодежи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240350680',0,'ЦСР_2016',1,'Субсидия на проведение Северо-Кавказского молодежного форума "Машук"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240360540',0,'ЦСР_2016',1,'Субсидии Фонду "Талант и успех", г. Сочи, Краснодарский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240400000',0,'ЦСР_2016',1,'Основное мероприятие "Создание условий успешной социализации и эффективной самореализации молодежи"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240460300',0,'ЦСР_2016',1,'Субсидии на государственную поддержку отдельных общественных организаций в сфере молодежной политики',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240500000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение мероприятий по содействию патриотическому воспитанию граждан Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240560300',0,'ЦСР_2016',1,'Субсидии на государственную поддержку отдельных общественных организаций в сфере молодежной политики',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0240600000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация механизмов развития молодежной политики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0250000000',0,'ЦСР_2016',1,'Подпрограмма "Совершенствование управления системой образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0250100000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация механизмов оценки и обеспечения качества образования в соответствии с государственными образовательными стандартами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0250200000',0,'ЦСР_2016',1,'Основное мероприятие "Поощрения педагогических работников за особые заслуги перед государством"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0250300000',0,'ЦСР_2016',1,'Основное мероприятие "Сопровождение реализации отдельных мероприятий государственной программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0280000000',0,'ЦСР_2016',1,'Федеральная целевая программа развития образования на 2016 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0280054980',0,'ЦСР_2016',1,'Субсидии на финансовое обеспечение мероприятий федеральной целевой программы развития образования на 2016 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0290000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Русский язык" на 2016 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0290054990',0,'ЦСР_2016',1,'Субсидии на финансовое обеспечение мероприятий федеральной целевой программы "Русский язык" на 2016 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0300000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Социальная поддержка граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение мер социальной поддержки отдельных категорий граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310100000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер государственной поддержки гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310130020',0,'ЦСР_2016',1,'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310130040',0,'ЦСР_2016',1,'Компенсация в возмещение вреда гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации всл',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310130050',0,'ЦСР_2016',1,'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 10 января 2002 года № 2-ФЗ "О социальных гарантиях гражданам, подвергшимся радиационному',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310130060',0,'ЦСР_2016',1,'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 26 ноября 1998 года           № 175-ФЗ "О социальной защите граждан Российской Федерации,',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310130080',0,'ЦСР_2016',1,'Компенсация в возмещение вреда гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Федеральным законом от 26 ноября 1998 года           № 175-ФЗ "О социальной защите граждан Российской Федерации, подвергшихся',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310130670',0,'ЦСР_2016',1,'Осуществление ежемесячной денежной выплаты гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подве',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310130700',0,'ЦСР_2016',1,'Осуществление ежемесячной денежной выплаты гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 10 января 2002 года № 2-ФЗ "О социальных гарантиях гражданам, подвергш',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310130710',0,'ЦСР_2016',1,'Осуществление ежемесячной денежной выплаты гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 26 ноября 1998 года № 175-ФЗ "О социальной защите граждан Российской Ф',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310130800',0,'ЦСР_2016',1,'Пособия гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации вследс',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310130880',0,'ЦСР_2016',1,'Пособия гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 10 января 2002 года № 2-ФЗ "О социальных гарантиях гражданам, подвергшимся радиационному воздействию всле',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310130890',0,'ЦСР_2016',1,'Пособия гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 26 ноября 1998 года            № 175-ФЗ "О социальной защите граждан Российской Федерации, подвергшихся в',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310151370',0,'ЦСР_2016',1,'Субвенции на осуществление переданных полномочий Российской Федерации по предоставлению отдельных мер социальной поддержки граждан, подвергшихся воздействию радиации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310200000',0,'ЦСР_2016',1,'Основное мероприятие "Предоставление мер государственной поддержки Героям Советского Союза, Героям Российской Федерации и полным кавалерам ордена Славы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310230090',0,'ЦСР_2016',1,'Социальная поддержка Героев Советского Союза, Героев Российской Федерации и полных кавалеров ордена Славы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310230300',0,'ЦСР_2016',1,'Дополнительное пожизненное ежемесячное материальное обеспечение Героям Советского Союза, Героям Российской Федерации и полным кавалерам ордена Славы - участникам Великой Отечественной войны 1941 - 1945 годов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310230720',0,'ЦСР_2016',1,'Осуществление ежемесячной денежной выплаты Героям Советского Союза, Героям Российской Федерации и полным кавалерам ордена Славы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310300000',0,'ЦСР_2016',1,'Основное мероприятие "Предоставление мер государственной поддержки Героям Социалистического Труда, Героям Труда Российской Федерации и полным кавалерам ордена Трудовой Славы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310330730',0,'ЦСР_2016',1,'Осуществление ежемесячной денежной выплаты Героям Социалистического Труда, Героям Труда Российской Федерации и полным кавалерам ордена Трудовой Славы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310351980',0,'ЦСР_2016',1,'Социальная поддержка Героев Социалистического Труда, Героев Труда Российской Федерации и полных кавалеров ордена Трудовой Славы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310400000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер социальной поддержки ветеранам Великой Отечественной войны и боевых действий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310430350',0,'ЦСР_2016',1,'Дополнительное ежемесячное материальное обеспечение некоторых категорий граждан Российской Федерации в связи с 60-летием Победы в Великой Отечественной войне 1941 - 1945 годов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310430690',0,'ЦСР_2016',1,'Осуществление ежемесячной денежной выплаты ветеранам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310430770',0,'ЦСР_2016',1,'Единовременная выплата отдельным категориям граждан в связи с празднованием 65-летия Победы в Великой Отечественной войне',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310430780',0,'ЦСР_2016',1,'Единовременная выплата некоторым категориям граждан Российской Федерации в связи с 67-летием Победы в Великой Отечественной войне 1941 - 1945 годов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310431170',0,'ЦСР_2016',1,'Единовременная выплата некоторым категориям граждан Российской Федерации в связи с 70-летием Победы в Великой Отечественной войне 1941 - 1945 годов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310500000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер государственной поддержки инвалидам"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310530360',0,'ЦСР_2016',1,'Дополнительное ежемесячное материальное обеспечение инвалидов вследствие военной травмы в соответствии с Указом Президента Российской Федерации от 1 августа 2005 года № 887 "О мерах по улучшению материального положения инвалидов вследствие военной тр',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310530680',0,'ЦСР_2016',1,'Осуществление ежемесячной денежной выплаты инвалидам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310600000',0,'ЦСР_2016',1,'Основное мероприятие "Предоставление отдельным категориям граждан государственной социальной помощи в виде набора социальных услуг в части санаторно-курортного лечения, проезда к месту лечения и обратно, а также проезда на железнодорожном транспорте',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310651930',0,'ЦСР_2016',1,'Оказание государственной социальной помощи отдельным категориям граждан в части оплаты санаторно-курортного лечения, а также проезда на междугородном транспорте к месту лечения и обратно',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310700000',0,'ЦСР_2016',1,'Основное мероприятие "Предоставление социальных доплат к пенсии"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310730570',0,'ЦСР_2016',1,'Выплата федеральной социальной доплаты к пенсии',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310751530',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на выплату региональной доплаты к пенсии',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310800000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер социальной поддержки по оплате жилищно-коммунальных услуг отдельным категориям граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310852500',0,'ЦСР_2016',1,'Субвенции на оплату жилищно-коммунальных услуг отдельным категориям граждан',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310900000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер государственной поддержки лицам, ходатайствующим о признании их беженцами или вынужденными переселенцами, а также прибывшим с ними членам их семей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310930100',0,'ЦСР_2016',1,'Пособие лицам, ходатайствующим о признании их беженцами на территории Российской Федерации, и прибывшим с ними членам их семей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0310930110',0,'ЦСР_2016',1,'Пособие лицам, ходатайствующим о признании их вынужденными переселенцами, и прибывшим с ними членам их семей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311000000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер государственной поддержки гражданам, пострадавшим в результате разрешения кризиса в Чеченской Республике и покинувшим ее безвозвратно"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311030470',0,'ЦСР_2016',1,'Компенсация за утраченное имущество гражданам, пострадавшим в результате разрешения кризиса в Чеченской Республике и покинувшим ее безвозвратно',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311100000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер социальной поддержки лицам, награжденным нагрудным знаком "Почетный донор России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311152200',0,'ЦСР_2016',1,'Субвенции на осуществление переданного полномочия Российской Федерации по осуществлению ежегодной денежной выплаты лицам, награжденным нагрудным знаком "Почетный донор России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311200000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер социальной поддержки гражданам при возникновении поствакцинальных осложнений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311252400',0,'ЦСР_2016',1,'Субвенции на выплату государственного единовременного пособия и ежемесячной денежной компенсации гражданам при возникновении поствакцинальных осложнений в соответствии с Федеральным законом от 17 сентября 1998 года № 157-ФЗ "Об иммунопрофилактике инф',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311300000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление компенсационных выплат реабилитированным лицам"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311353000',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на единовременные денежные компенсации реабилитированным лицам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311400000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание поддержки в связи с погребением умерших"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311430140',0,'ЦСР_2016',1,'Возмещение федеральными органами исполнительной власти расходов на погребение',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311430740',0,'ЦСР_2016',1,'Выплата социального пособия на погребение и оказание услуг по погребению согласно гарантированному перечню этих услуг за умерших, получавших пенсии по государственному пенсионному обеспечению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311430750',0,'ЦСР_2016',1,'Выплата социального пособия на погребение и оказание услуг по погребению согласно гарантированному перечню этих услуг за умерших, получавших страховую или накопительную пенсии',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311430760',0,'ЦСР_2016',1,'Выплата социального пособия на погребение умерших неработавших пенсионеров, досрочно оформивших пенсию по предложению органов службы занятости, и оказание услуг по погребению согласно гарантированному перечню этих услуг',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311430900',0,'ЦСР_2016',1,'Возмещение стоимости гарантированного перечня услуг и социальные пособия на погребение за счет средств Фонда социального страхования Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311431080',0,'ЦСР_2016',1,'Возмещение органами прокуратуры Российской Федерации расходов на погребение',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311500000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер государственной поддержки отдельным категориям государственных служащих, а также уволенным из их числа и членам их семей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311530130',0,'ЦСР_2016',1,'Пособия лицам, досрочно уволенным из органов федеральной противопожарной службы Государственной противопожарной службы, и членам семей погибших (умерших) сотрудников и работников федеральной противопожарной службы Государственной противопожарной служ',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311530170',0,'ЦСР_2016',1,'Пособия, выплаты и компенсации членам семей военнослужащих, а также лицам, уволенным с военной службы без права на пенсию',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311530180',0,'ЦСР_2016',1,'Пособия, выплаты и компенсации лицам, уволенным с военной службы с правом на пенсию, а также членам их семей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311530310',0,'ЦСР_2016',1,'Ежемесячные социальные пособия лицам, уволенным из органов по контролю за оборотом наркотических средств и психотропных веществ без права на пенсию',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311600000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер государственной поддержки отдельным категориям государственных служащих, гражданам в связи с исполнением обязанностей военной службы по призыву, получившим увечье или иное повреждение здоровья, а также членам их сем',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311630120',0,'ЦСР_2016',1,'Пособия лицам, являвшимся сотрудниками федеральной фельдъегерской связи, получившим телесные повреждения, исключающие для них возможность дальнейшего осуществления служебной деятельности, а также семьям и иждивенцам погибших (умерших) сотрудников фед',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311630150',0,'ЦСР_2016',1,'Пособия лицам, являвшимся сотрудниками учреждений и органов уголовно-исполнительной системы, федеральной противопожарной службы Государственной противопожарной службы, органов по контролю за оборотом наркотических средств и психотропных веществ, тамо',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311630160',0,'ЦСР_2016',1,'Компенсации лицам, являвшимся судебными приставами, утратившим возможность заниматься профессиональной деятельностью, и нетрудоспособным членам семей погибших (умерших) судебных приставов',0,'',0,'','', '19000101',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 '0311630210',0,'ЦСР_2016',1,'Пособия гражданам, являвшимся должностными лицами таможенных органов, утратившим возможность заниматься профессиональной деятельностью, и членам семьи и иждивенцам должностного лица таможенных органов в случае его гибели в связи с исполнением служебн',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311630220',0,'ЦСР_2016',1,'Компенсации лицам, являвшимся сотрудниками Следственного комитета Российской Федерации, утратившим возможность заниматься профессиональной деятельностью, и членам семей погибших (умерших) сотрудников Следственного комитета Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311630240',0,'ЦСР_2016',1,'Пособия и компенсации членам семей погибших (умерших) военнослужащих (граждан, проходивших военные сборы, инвалидов вследствие военной травмы), а также лицам, которым установлена инвалидность вследствие военной травмы после увольнения с военной служб',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311630250',0,'ЦСР_2016',1,'Пособия лицам, являвшимся сотрудниками органов внутренних дел, получившим телесные повреждения, исключающие возможность дальнейшего прохождения службы, а также семьям и иждивенцам сотрудников органов внутренних дел, погибших (умерших) в связи с осуще',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311630990',0,'ЦСР_2016',1,'Пособия и компенсации членам семей, а также родителям погибших (умерших) сотрудников органов внутренних дел',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311631140',0,'ЦСР_2016',1,'Пособия лицам, являвшимся спасателями профессиональных аварийно-спасательных служб, профессиональных аварийно-спасательных формирований, получившим увечья, исключающие возможность дальнейшей работы спасателем, а также членам семей спасателей, погибши',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311700000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание государственной поддержки членам семей лиц, погибших при осуществлении мероприятий по борьбе с терроризмом, а также лицам, получившим увечья при осуществлении указанных мероприятий, повлекшие наступление инвалидности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311730200',0,'ЦСР_2016',1,'Единовременное пособие членам семей (лицам, находившимся на их иждивении) лиц, погибших при осуществлении мероприятий по борьбе с терроризмом, а также лицам, получившим увечья при осуществлении мероприятий по борьбе с терроризмом, повлекшие наступлен',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311800000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление компенсационных выплат лицам, осуществляющим уход за нетрудоспособными гражданами и детьми-инвалидами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311830390',0,'ЦСР_2016',1,'Компенсационные выплаты лицам, осуществляющим уход за нетрудоспособными гражданами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311830980',0,'ЦСР_2016',1,'Оплата четырех дополнительных выходных дней работающим родителям (опекунам, попечителям) для ухода за детьми-инвалидами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311831030',0,'ЦСР_2016',1,'Ежемесячные выплаты лицам, осуществляющим уход за детьми-инвалидами и инвалидами с детства I группы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311900000',0,'ЦСР_2016',1,'Основное мероприятие "Выплата дополнительного материального обеспечения гражданам за выдающиеся достижения и особые заслуги перед Российской Федерацией"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0311930190',0,'ЦСР_2016',1,'Выплата дополнительного материального обеспечения, доплат к пенсиям, пособий и компенсаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312000000',0,'ЦСР_2016',1,'Основное мероприятие "Страховое обеспечение по обязательному социальному страхованию от несчастных случаев на производстве и профессиональных заболеваний"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312030960',0,'ЦСР_2016',1,'Единовременные страховые выплаты',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312030970',0,'ЦСР_2016',1,'Ежемесячные страховые выплаты',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312039610',0,'ЦСР_2016',1,'Доставка и пересылка страховых выплат',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312039630',0,'ЦСР_2016',1,'Медицинская, социальная и профессиональная реабилитация пострадавших, обеспечение предупредительных мер по сокращению производственного травматизма и профессиональных заболеваний',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312100000',0,'ЦСР_2016',1,'Основное мероприятие "Предоставление отдельным категориям граждан государственной социальной помощи на основании социального контракта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312200000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование законодательства в области предоставления мер социальной поддержки отдельных категорий граждан и системы социального страхования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312300000',0,'ЦСР_2016',1,'Основное мероприятие "Создание единой информационной базы данных лиц, получивших средства федерального бюджета на улучшение жилищных условий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312400000',0,'ЦСР_2016',1,'Основное мероприятие "Предоставление пособий по временной нетрудоспособности по обязательному социальному страхованию"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312430910',0,'ЦСР_2016',1,'Пособия по временной нетрудоспособности по обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312430950',0,'ЦСР_2016',1,'Пособия по временной нетрудоспособности по обязательному социальному страхованию от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312500000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение обязательного социального страхования на случай временной нетрудоспособности и в связи с материнством"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312600000',0,'ЦСР_2016',1,'Основное мероприятие "Предоставление пособий по обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством гражданам в связи с зачетом в страховой стаж нестраховых периодов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312630940',0,'ЦСР_2016',1,'Пособия по временной нетрудоспособности отдельным категориям граждан в связи с зачетом в страховой стаж нестраховых периодов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0312631040',0,'ЦСР_2016',1,'Пособия по беременности и родам отдельным категориям граждан в связи с зачетом в страховой стаж нестраховых периодов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0320000000',0,'ЦСР_2016',1,'Подпрограмма "Модернизация и развитие социального обслуживания населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0320100000',0,'ЦСР_2016',1,'Основное мероприятие "Распространение положительного опыта работы субъектов Российской Федерации в сфере социального обслуживания граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0320200000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование независимой системы оценки качества работы организаций, оказывающих социальные услуги в сфере социального обслуживания населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0320300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение деятельности учреждений социального обслуживания граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0320400000',0,'ЦСР_2016',1,'Основное мероприятие "Поощрение победителей Всероссийского конкурса на звание "Лучший работник учреждений социального обслуживания"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0320500000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы оплаты труда социальных работников"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0320600000',0,'ЦСР_2016',1,'Основное мероприятие "Привлечение в сферу социального обслуживания населения бизнеса и социально ориентированных некоммерческих организаций, благотворителей и добровольцев"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0320700000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание финансовой поддержки бюджетам субъектов Российской Федерации на осуществление мероприятий по укреплению материально-технической базы организаций социального обслуживания"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0320800000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы социального обслуживания граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение государственной поддержки семей, имеющих детей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330100000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер государственной поддержки в связи с беременностью и родами, а также гражданам, имеющим детей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330130530',0,'ЦСР_2016',1,'Компенсации женщинам, имеющим детей в возрасте до трех лет, уволенным в связи с ликвидацией организации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330130820',0,'ЦСР_2016',1,'Пособия по уходу за ребенком до достижения им возраста полутора лет гражданам, подлежащим обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330130830',0,'ЦСР_2016',1,'Пособия при рождении ребенка гражданам, подлежащим обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330130840',0,'ЦСР_2016',1,'Единовременные пособия женщинам, вставшим на учет в медицинских учреждениях в ранние сроки беременности, подлежащим обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330130920',0,'ЦСР_2016',1,'Пособия по беременности и родам гражданам, подлежащим обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330152700',0,'ЦСР_2016',1,'Субвенции на выплату единовременного пособия беременной жене военнослужащего, проходящего военную службу по призыву, а также ежемесячного пособия на ребенка военнослужащего, проходящего военную службу по призыву, в соответствии с Федеральным законом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330153800',0,'ЦСР_2016',1,'Субвенции на выплату государственных пособий лицам, не подлежащим обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством, и лицам, уволенным в связи с ликвидацией организаций (прекращением деятельности,',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение выплаты пособий по уходу за ребенком гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330230030',0,'ЦСР_2016',1,'Пособие по уходу за ребенком гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации вслед',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330230070',0,'ЦСР_2016',1,'Пособие по уходу за ребенком гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Федеральным законом от 26 ноября 1998 года           № 175-ФЗ "О социальной защите граждан Российской Федерации, подвергшихся в',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение выплаты ежемесячных пособий и пособий на проведение летнего оздоровительного отдыха детям погибших (умерших) военнослужащих и сотрудников некоторых федеральных органов исполнительной власти"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330330260',0,'ЦСР_2016',1,'Ежемесячное пособие детям военнослужащих и сотрудников некоторых федеральных органов исполнительной власти, погибших (умерших, объявленных умершими, признанных безвестно отсутствующими) при исполнении обязанностей военной службы (служебных обязанност',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330330550',0,'ЦСР_2016',1,'Пособие на проведение летнего оздоровительного отдыха детей отдельных категорий военнослужащих и сотрудников некоторых федеральных органов исполнительной власти, погибших (умерших), пропавших без вести, ставших инвалидами в связи с выполнением задач',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330331060',0,'ЦСР_2016',1,'Ежемесячное пособие на содержание детей и ежегодное пособие на проведение летнего оздоровительного отдыха детей сотрудников учреждений и органов уголовно-исполнительной системы, федеральной противопожарной службы Государственной противопожарной служб',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330400000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание социальной поддержки многодетным семьям"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330450840',0,'ЦСР_2016',1,'Субсидии на ежемесячную денежную выплату, назначаемую в случае рождения третьего ребенка или последующих детей до достижения ребенком возраста трех лет',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330451550',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на единовременное денежное поощрение при награждении орденом "Родительская слава"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330500000',0,'ЦСР_2016',1,'Основное мероприятие "Предоставление материнского (семейного) капитала"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330530790',0,'ЦСР_2016',1,'Предоставление материнского (семейного) капитала',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330539730',0,'ЦСР_2016',1,'Направление средств материнского (семейного) капитала, ранее направленных на формирование накопительной пенсии, на улучшение жилищных условий и получение образования ребенком (детьми)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330600000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание поддержки бюджетам субъектов Российской Федерации на проведение мероприятий по отдыху и оздоровлению детей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330700000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер социальной поддержки детям-сиротам, детям, оставшимся без попечения родителей, лицам из числа указанной категории детей, а также гражданам, желающим взять детей на воспитание в семью"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330750820',0,'ЦСР_2016',1,'Субсидии на предоставление жилых помещений детям-сиротам и детям, оставшимся без попечения родителей, лицам из их числа по договорам найма специализированных жилых помещений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330752600',0,'ЦСР_2016',1,'Субвенции на выплату единовременного пособия при всех формах устройства детей, лишенных родительского попечения, в семью',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330800000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание поддержки детям, оказавшимся в трудной жизненной ситуации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0330900000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование нормативной правовой базы по предоставлению мер государственной поддержки семьям, имеющим детей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0331000000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование  системы социального обслуживания семей с детьми"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0340000000',0,'ЦСР_2016',1,'Подпрограмма "Повышение эффективности государственной поддержки социально ориентированных некоммерческих организаций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0340100000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание государственной поддержки общественным и иным некоммерческим организациям"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0340160210',0,'ЦСР_2016',1,'Субсидии на возмещение затрат, связанных с осуществлением деятельности, направленной на решение социальных вопросов, защиту прав и законных интересов граждан',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0340200000',0,'ЦСР_2016',1,'Основное мероприятие "Организация статистических обследований и переписей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0340300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение деятельности Комитета ветеранов подразделений особого риска Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0360000000',0,'ЦСР_2016',1,'Подпрограмма "Старшее поколение"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0360100000',0,'ЦСР_2016',1,'Основное мероприятие "Софинансирование социальных программ субъектов Российской Федерации, связанных с укреплением материально-технической базы учреждений социального обслуживания населения и оказанием адресной социальной помощи неработающим пенсионе',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0360152090',0,'ЦСР_2016',1,'Софинансирование социальных программ субъектов Российской Федерации, связанных с укреплением материально-технической базы учреждений социального обслуживания населения, оказанием адресной социальной помощи неработающим пенсионерам, обучением компьюте',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0360200000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание  мер социальной поддержки пенсионерам в районах Крайнего Севера и приравненных к ним местностях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0360231150',0,'ЦСР_2016',1,'Компенсация расходов, связанных с переездом из районов Крайнего Севера и приравненных к ним местностей в другую местность на территории Российской Федерации в соответствии с законодательством Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0360251990',0,'ЦСР_2016',1,'Оплата стоимости проезда пенсионерам к месту отдыха и обратно один раз в два года',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0370000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение условий реализации государственной программы Российской Федерации  "Социальная поддержка граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0370100000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-методическое и материальное обеспечение государственной политики в сфере социальной поддержки населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0370200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение выполнения полномочий Фонда социального страхования Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0370300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие международного сотрудничества в  сфере социальной поддержки граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0400000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Доступная среда" на 2011 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0410000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение условий доступности приоритетных объектов и услуг в приоритетных сферах жизнедеятельности инвалидов и других маломобильных групп населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0410100000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативно-правовое и организационно-методическое обеспечение реализации мероприятий  в области формирования доступной среды"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0410200000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие реализации мероприятий субъектов Российской Федерации в сфере обеспечения доступности приоритетных объектов и услуг в приоритетных сферах жизнедеятельности инвалидов и других маломобильных групп населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0410300000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация мероприятий, направленных на расширение использования русского жестового языка"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0410400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение информационной доступности для инвалидов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0410464990',0,'ЦСР_2016',1,'Субсидии издательствам и издающим организациям на реализацию социально значимых проектов, выпуск книг, изданий, в том числе учебников и учебных пособий, для инвалидов по зрению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0410465010',0,'ЦСР_2016',1,'Субсидии редакциям печатных средств массовой информации и издающим организациям для инвалидов по зрению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0410465020',0,'ЦСР_2016',1,'Субсидии редакциям печатных средств массовой информации и издающим организациям для инвалидов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0410500000',0,'ЦСР_2016',1,'Основное мероприятие "Организация социологических исследований и общественно-просветительских кампаний в сфере формирования доступной среды для инвалидов и других маломобильных групп населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420000000',0,'ЦСР_2016',1,'Подпрограмма "Совершенствование системы комплексной реабилитации и абилитации инвалидов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420100000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативно-правовое и организационно-методическое обеспечение реализации мероприятий, направленных на совершенствование комплексной реабилитации и абилитации инвалидов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420200000',0,'ЦСР_2016',1,'Основное мероприятие "Предоставление государственных гарантий инвалидам"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420239570',0,'ЦСР_2016',1,'Обеспечение инвалидов техническими средствами реабилитации, включая изготовление и ремонт протезно-ортопедических изделий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420251300',0,'ЦСР_2016',1,'Субвенции на обеспечение инвалидов техническими средствами реабилитации, включая изготовление и ремонт протезно-ортопедических изделий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420252800',0,'ЦСР_2016',1,'Субвенции на выплату инвалидам компенсаций страховых премий по договорам обязательного страхования гражданской ответственности владельцев транспортных средств в соответствии с Федеральным законом от 25 апреля 2002 года № 40-ФЗ "Об обязательном страхо',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420265030',0,'ЦСР_2016',1,'Субсидии стационарам сложного протезирования на оплату дней пребывания инвалидов в стационарах',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420265040',0,'ЦСР_2016',1,'Субсидии федеральным государственным унитарным протезно-ортопедическим предприятиям на возмещение убытков, связанных с реализацией протезно-ортопедических изделий и услуг по протезированию по ценам ниже себестоимости',0,'',0,'','', '19000101',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 '0420300000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение квалификации специалистов в сфере реабилитации и абилитации инвалидов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420400000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание государственной поддержки общественным организациям инвалидов и иным некоммерческим организациям"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420460210',0,'ЦСР_2016',1,'Субсидии на возмещение затрат, связанных с осуществлением деятельности, направленной на решение социальных вопросов, защиту прав и законных интересов граждан',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420460220',0,'ЦСР_2016',1,'Субсидии общественным организациям инвалидов на поддержку программ по содействию трудоустройству инвалидов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420462470',0,'ЦСР_2016',1,'Субсидии на государственную поддержку общероссийских общественных организаций инвалидов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420500000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация мероприятий, направленных на формирование современной отечественной отрасли производства товаров для инвалидов, в том числе средств реабилитации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0420600000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие реализации мероприятий субъектов Российской Федерации в сфере реабилитации и абилитации инвалидов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0430000000',0,'ЦСР_2016',1,'Подпрограмма "Совершенствование государственной системы медико-социальной экспертизы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0430100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование организации и проведения медико-социальной экспертизы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0430200000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение квалификации специалистов учреждений медико-социальной экспертизы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0430300000',0,'ЦСР_2016',1,'Основное мероприятие "Организация и проведение пилотных проектов в субъектах Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0430400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение деятельности учреждений медико-социальной экспертизы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0430500000',0,'ЦСР_2016',1,'Основное мероприятие "Укрепление материально-технической базы учреждений медико-социальной экспертизы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0500000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Обеспечение доступным и комфортным жильем и коммунальными услугами граждан Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510000000',0,'ЦСР_2016',1,'Подпрограмма "Создание условий для обеспечения доступным и комфортным жильем граждан России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510100000',0,'ЦСР_2016',1,'Основное мероприятие "Переселение граждан из многоквартирных домов, признанных аварийными и подлежащими сносу и не входящих в действующие программы переселения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510165120',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в государственную корпорацию - Фонд содействия реформированию жилищно-коммунального хозяйства для увеличения лимитов предоставления финансовой поддержки субъектам Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510200000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование управления специальными жилищными программами с использованием ипотечного кредитования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение жильем отдельных категорий граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510351340',0,'ЦСР_2016',1,'Субвенции на осуществление полномочий по обеспечению жильем отдельных категорий граждан, установленных Федеральным законом от 12 января 1995 года № 5-ФЗ "О ветеранах", в соответствии с Указом от 7 мая 2008 года № 714 "Об обеспечении жильем ветеранов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510351350',0,'ЦСР_2016',1,'Субвенции на осуществление полномочий по обеспечению жильем отдельных категорий граждан, установленных федеральными законами от 12 января 1995 года № 5-ФЗ "О ветеранах" и от 24 ноября 1995 года № 181-ФЗ "О социальной защите инвалидов в Российской Фед',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510400000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация программы "Жилье для российской семьи"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510500000',0,'ЦСР_2016',1,'Основное мероприятие "Создание условий для развития жилищного строительства на вовлекаемых в гражданский оборот земельных участках в соответствии с Федеральным законом "О содействии развитию жилищного строительства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510600000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование механизмов долгосрочного финансирования ипотечного жилищного кредитования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510700000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие формированию рынка доступного арендного жилья и развитие некоммерческого жилищного фонда для граждан, имеющих невысокий уровень дохода"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510800000',0,'ЦСР_2016',1,'Основное мероприятие "Внедрение новых энергоэффективных и ресурсосберегающих технологий при жилищном строительстве, создание условий для строительства и реконструкции предприятий по производству ресурсосберегающих материалов, изделий и конструкций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0510900000',0,'ЦСР_2016',1,'Основное мероприятие "Восстановление и (или) проведение капитального ремонта жилищного фонда (переселение граждан из жилищного фонда), поврежденного (признанного непригодным для проживания) вследствие чрезвычайных ситуаций природного и техногенного х',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0520000000',0,'ЦСР_2016',1,'Подпрограмма "Создание условий для обеспечения качественными услугами жилищно-коммунального хозяйства граждан России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0520100000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие проведению капитального ремонта многоквартирных домов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0520200000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка региональных программ модернизации систем коммунальной инфраструктуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0520300000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация проекта Международного банка реконструкции и развития "Реформа жилищно-коммунального хозяйства в России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0520400000',0,'ЦСР_2016',1,'Основное мероприятие "Стимулирование рационального потребления коммунальных услуг населением"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0520500000',0,'ЦСР_2016',1,'Основное мероприятие "Подготовка коммунальной инфраструктуры, обеспечивающей функционирование спортивных объектов, в рамках проведения в 2018 году в Российской Федерации чемпионата мира по футболу"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0520550300',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий по подготовке и проведению чемпионата мира по футболу в 2018 году в Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0520600000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие развитию коммунальной и инженерной инфраструктуры государственной собственности субъектов Российской Федерации (муниципальной собственности)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0530000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Обеспечение доступным и комфортным жильем и коммунальными услугами граждан Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0530100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение функций центрального аппарата Минстроя России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0530200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение устойчивого развития жилищного сектора и инфраструктуры населенных пунктов (Программа ООН "ХАБИТАТ")"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0530300000',0,'ЦСР_2016',1,'Основное мероприятие "Премирование победителей Всероссийского конкурса на звание "Самое благоустроенное городское (сельское) поселение России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0530400000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы государственного ценообразования, сметного нормирования и технического регулирования в строительной сфере"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Жилище" на  2015 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540100000',0,'ЦСР_2016',1,'Подпрограмма "Модернизация объектов коммунальной инфраструктуры" федеральной целевой программы "Жилище" на 2015 - 2020  годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540150220',0,'ЦСР_2016',1,'Субсидии на мероприятия подпрограммы "Модернизация объектов коммунальной инфраструктуры" федеральной целевой программы "Жилище" на 2015 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540200000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение жильем молодых семей" федеральной целевой программы "Жилище" на 2015 - 2020  годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540250200',0,'ЦСР_2016',1,'Субсидии на мероприятия подпрограммы "Обеспечение жильем молодых семей" федеральной целевой программы "Жилище" на 2015 - 2020  годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540300000',0,'ЦСР_2016',1,'Подпрограмма "Выполнение государственных обязательств по обеспечению жильем категорий граждан, установленных федеральным законодательством" федеральной целевой программы "Жилище" на 2015 - 2020  годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540335700',0,'ЦСР_2016',1,'Приобретение жилья гражданами, подлежащими переселению из закрытых административно-территориальных образований и территорий, ранее входивших в границы закрытых административно-территориальных образований',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540335840',0,'ЦСР_2016',1,'Приобретение жилья военнослужащими, сотрудниками органов внутренних дел, подлежащими увольнению с военной службы (службы), и приравненными к ним лицами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540335860',0,'ЦСР_2016',1,'Приобретение жилья гражданами - участниками ликвидации последствий радиационных аварий и катастроф, пострадавшими в результате этих аварий, и приравненными к ним лицами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540335870',0,'ЦСР_2016',1,'Приобретение жилья вынужденными переселенцами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540335880',0,'ЦСР_2016',1,'Приобретение жилья гражданами, выезжающими из районов Крайнего Севера и приравненных к ним местностей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540354850',0,'ЦСР_2016',1,'Субвенции на обеспечение жильем граждан, уволенных с военной службы (службы), и приравненных к ним лиц',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540400000',0,'ЦСР_2016',1,'Подпрограмма "Стимулирование программ развития жилищного строительства субъектов Российской Федерации" федеральной целевой программы "Жилище" на 2015 - 2020   годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540450210',0,'ЦСР_2016',1,'Субсидии на мероприятия подпрограммы "Стимулирование программ развития жилищного строительства субъектов Российской Федерации" федеральной целевой программы "Жилище" на 2015 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540500000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение жильем отдельных категорий граждан" федеральной целевой программы "Жилище" на 2015 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540535890',0,'ЦСР_2016',1,'Мероприятия по обеспечению жильем федеральных государственных гражданских служащих',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540535900',0,'ЦСР_2016',1,'Мероприятия по обеспечению жильем прокуроров и следователей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540535920',0,'ЦСР_2016',1,'Мероприятия по обеспечению жильем молодых ученых и строительство общежитий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540535930',0,'ЦСР_2016',1,'Мероприятия по обеспечению жильем иных категорий граждан Управлением делами Президента Российской Федерации на основании решений Президента Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540550230',0,'ЦСР_2016',1,'Субсидии на мероприятия по переселению граждан из ветхого и аварийного жилья в зоне Байкало-Амурской магистрали',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540550240',0,'ЦСР_2016',1,'Субсидии на мероприятия по приведению объектов города Волгодонска в состояние, обеспечивающее безопасное проживание его жителей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540554960',0,'ЦСР_2016',1,'Субсидии на мероприятия по переселению граждан, проживающих в оползневой зоне Малгобекского района Республики Ингушетия',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0540567380',0,'ЦСР_2016',1,'Субсидии российским кредитным организациям и акционерному обществу "Агентство по ипотечному жилищному кредитованию" на возмещение недополученных доходов по выданным (приобретенным) жилищным (ипотечным) кредитам (займам)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0549900000',0,'ЦСР_2016',1,'Реализация мероприятий общепрограммного характера по федеральной целевой программе',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0550000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Чистая вода" на 2011 - 2017 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0700000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Содействие занятости населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0710000000',0,'ЦСР_2016',1,'Подпрограмма "Активная политика занятости населения и социальная поддержка безработных граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0710100000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка нормативной правовой и методической базы в сфере занятости населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0710200000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация мероприятий активной политики занятости населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0710300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие трудовой мобильности населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0710352380',0,'ЦСР_2016',1,'Субсидии на софинансирование региональных программ повышения мобильности трудовых ресурсов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0710400000',0,'ЦСР_2016',1,'Основное мероприятие "Мониторинг состояния и разработка прогнозных оценок рынка труда"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0710500000',0,'ЦСР_2016',1,'Основное мероприятие "Социальные выплаты безработным гражданам и оптимизация критериев назначения и размеров пособия по безработице"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0710552900',0,'ЦСР_2016',1,'Субвенции на социальные выплаты безработным гражданам в соответствии с Законом Российской Федерации от 19 апреля 1991 года № 1032-I "О занятости населения в Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0720000000',0,'ЦСР_2016',1,'Подпрограмма "Внешняя трудовая миграция"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0720100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование миграционного законодательства в части привлечения и использования иностранных работников"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0720200000',0,'ЦСР_2016',1,'Основное мероприятие "Использование дифференцированного подхода к привлечению и использованию иностранных работников"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0720300000',0,'ЦСР_2016',1,'Основное мероприятие "Противодействие незаконной трудовой деятельности иностранных работников в Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0720400000',0,'ЦСР_2016',1,'Основное мероприятие "Организация государственной информационной системы миграционного учета"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0720500000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие развитию и реализации программ по адаптации и интеграции иностранных граждан в российское общество"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0730000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие институтов рынка труда"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0730100000',0,'ЦСР_2016',1,'Основное мероприятие "Создание условий для улучшения качества рабочей силы и развития ее профессиональной мобильности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0730167260',0,'ЦСР_2016',1,'Субсидия автономной некоммерческой организации "Национальное агентство развития квалификаций" на формирование и актуализацию базы данных востребованных на рынке труда новых и перспективных профессий, а также на создание и сопровождение интернет - рес',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0730168280',0,'ЦСР_2016',1,'Субсидия Общероссийскому объединению работодателей "Российский союз промышленников и предпринимателей" на организацию разработки и актуализации профессиональных стандартов для коммерческих организаций, внедрение и сопровождение системы оценки професс',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0730168840',0,'ЦСР_2016',1,'Субсидии союзу "Агентство развития профессиональных сообществ и рабочих кадров "Ворлдскиллс Россия" на выполнение функций базового центра профессиональной подготовки, переподготовки и повышения квалификации рабочих кадров',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0730200000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие увеличению размера реальной заработной платы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0730300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие социального партнерства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0730400000',0,'ЦСР_2016',1,'Основное мероприятие "Стимулирование работодателей к улучшению условий труда на рабочих местах"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0730500000',0,'ЦСР_2016',1,'Основное мероприятие "Надзор и контроль в сфере труда и занятости"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0730554350',0,'ЦСР_2016',1,'Субвенции бюджетам Республики Крым и города федерального значения Севастополя на осуществление части переданных полномочий Российской Федерации в сфере трудового законодательства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0740000000',0,'ЦСР_2016',1,'Подпрограмма "Оказание содействия добровольному переселению в Российскую Федерацию соотечественников, проживающих за рубежом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0740100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование нормативной правовой базы в сфере оказания содействия добровольному переселению в Российскую Федерацию соотечественников, проживающих за рубежом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0740200000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие реализации региональных программ переселения, включенных в Государственную программу по оказанию содействия добровольному переселению в Российскую Федерацию соотечественников, проживающих за рубежом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0740250860',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий, предусмотренных региональной программой переселения, включенной в Государственную программу по оказанию содействия добровольному переселению в Российскую Федерацию соотечественников, проживающих за рубежом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0740300000',0,'ЦСР_2016',1,'Основное мероприятие "Деятельность временных групп за рубежом, а также их инспектирование"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0740400000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание мер государственной поддержки участникам Государственной программы по оказанию содействия добровольному переселению в Российскую Федерацию соотечественников, проживающих за рубежом, и членов их семей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0740500000',0,'ЦСР_2016',1,'Основное мероприятие "Аналитическое и организационно-методическое обеспечение реализации Государственной программы по оказанию содействия добровольному переселению в Российскую Федерацию соотечественников, проживающих за рубежом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0740600000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование нормативной правовой базы субъектов Российской Федерации по вопросам реализации соответствующей региональной программы переселения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0800000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Обеспечение общественного порядка и противодействие преступности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0810000000',0,'ЦСР_2016',1,'Подпрограмма "Предварительное следствие"',0,'',0,'','', '19000101',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 '0810100000',0,'ЦСР_2016',1,'Основное мероприятие "Организационно-методическое руководство деятельностью подчиненных органов предварительного следствия"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0810200000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление ведомственного процессуального контроля"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0810300000',0,'ЦСР_2016',1,'Основное мероприятие "Организация расследования преступлений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0820000000',0,'ЦСР_2016',1,'Подпрограмма "Полиция"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0820100000',0,'ЦСР_2016',1,'Основное мероприятие "Антикриминальная деятельность"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0820200000',0,'ЦСР_2016',1,'Основное мероприятие "Охрана общественного порядка и профилактика правонарушений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0820300000',0,'ЦСР_2016',1,'Основное мероприятие "Взаимодействие и сотрудничество правоохранительных и иных государственных органов Российской Федерации с правоохранительными органами иностранных государств - членов Международной организации уголовной полиции - Интерпола, Генер',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0820400000',0,'ЦСР_2016',1,'Основное мероприятие "Экспертно-криминалистическая деятельность"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0820500000',0,'ЦСР_2016',1,'Основное мероприятие "Дознание"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0820600000',0,'ЦСР_2016',1,'Основное мероприятие "Содержание, охрана и конвоирование лиц, подозреваемых и обвиняемых в совершении преступлений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0820700000',0,'ЦСР_2016',1,'Основное мероприятие "Деятельность подразделений специального назначения и авиации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0820800000',0,'ЦСР_2016',1,'Основное мероприятие "Охрана на договорной основе имущества граждан и организаций, а также объектов, подлежащих обязательной охране полицией"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0820900000',0,'ЦСР_2016',1,'Основное мероприятие "Государственный контроль в сфере оборота оружия и частной детективной (сыскной) и охранной деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0821000000',0,'ЦСР_2016',1,'Основное мероприятие "Деятельность дежурных частей органов внутренних дел Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0821100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение безопасности на транспорте"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0821200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение безопасности дорожного движения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0821300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение подготовки кадров для органов внутренних дел Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0821400000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация Государственной программы "Обеспечение безопасности потерпевших, свидетелей и иных участников уголовного судопроизводства на 2014 - 2018 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0830000000',0,'ЦСР_2016',1,'Подпрограмма "Внутренние войска Министерства внутренних дел Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0830100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы комплектования и организации служебно-боевой деятельности внутренних войск МВД России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0830200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение подготовки кадров для внутренних войск МВД России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0840000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Обеспечение общественного порядка и противодействие преступности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0840100000',0,'ЦСР_2016',1,'Основное мероприятие "Создание условий для формирования позитивного облика сотрудника органов внутренних дел и повышения уровня доверия к органам внутренних дел со стороны населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0840200000',0,'ЦСР_2016',1,'Основное мероприятие "Административное обеспечение"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0840300000',0,'ЦСР_2016',1,'Основное мероприятие "Тыловое обеспечение"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0840400000',0,'ЦСР_2016',1,'Основное мероприятие "Медицинское обеспечение"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0840500000',0,'ЦСР_2016',1,'Основное мероприятие "Жилищное обеспечение"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0850000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Повышение безопасности дорожного движения в 2013 - 2020 годах"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0900000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Противодействие незаконному обороту наркотиков"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0910000000',0,'ЦСР_2016',1,'Подпрограмма "Комплексные меры противодействия незаконному обороту наркотиков"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0910100000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация функций органов наркоконтроля"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0910200000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение оперативно-розыскных мероприятий, направленных на выявление, предупреждение, пресечение и раскрытие преступлений, связанных с незаконным оборотом наркотических средств и психотропных веществ"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0910300000',0,'ЦСР_2016',1,'Основное мероприятие "Международное сотрудничество в сфере борьбы с незаконным оборотом наркотиков"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0910400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение научной деятельности в интересах органов наркоконтроля"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0910500000',0,'ЦСР_2016',1,'Основное мероприятие "Жилищное обеспечение сотрудников органов наркоконтроля"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0910600000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации образовательных программ в интересах органов наркоконтроля"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0910700000',0,'ЦСР_2016',1,'Основное мероприятие "Медицинское обеспечение сотрудников органов наркоконтроля"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0920000000',0,'ЦСР_2016',1,'Подпрограмма "Координация антинаркотической деятельности федеральных органов исполнительной власти и органов исполнительной власти субъектов Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0920100000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение профилактических мероприятий и реализация государственных мер по усилению противодействия потреблению наркотиков"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0920200000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование государственной системы мониторинга наркоситуации в Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0930000000',0,'ЦСР_2016',1,'Подпрограмма "Комплексная реабилитация и ресоциализация лиц, потребляющих наркотические средства и психотропные вещества в немедицинских целях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0930100000',0,'ЦСР_2016',1,'Основное мероприятие "Создание федеральной инфраструктуры комплексной реабилитации и ресоциализации лиц, потребляющих  наркотические средства и психотропные вещества в немедицинских целях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0930160910',0,'ЦСР_2016',1,'Субсидии социально ориентированным некоммерческим организациям, осуществляющим деятельность в области комплексной реабилитации и ресоциализации  лиц, осуществляющих незаконное потребление наркотических средств или психотропных веществ',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '0930200000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка реализации региональных проектов по развитию инфраструктуры комплексной реабилитации и ресоциализации лиц, потребляющих  наркотические средства и психотропные вещества в немедицинских целях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1000000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Защита населения и территорий от чрезвычайных ситуаций, обеспечение пожарной безопасности и безопасности людей на водных объектах"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010000000',0,'ЦСР_2016',1,'Подпрограмма "Предупреждение, спасение, помощь"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010100000',0,'ЦСР_2016',1,'Основное мероприятие "Управление средствами резервного фонда Правительства Российской Федерации по предупреждению и ликвидации чрезвычайных ситуаций и последствий стихийных бедствий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010120570',0,'ЦСР_2016',1,'Резервный фонд Правительства Российской Федерации по предупреждению и ликвидации чрезвычайных ситуаций и последствий стихийных бедствий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010200000',0,'ЦСР_2016',1,'Основное мероприятие "Подготовка и реализация неотложных и внеплановых мероприятий по предупреждению и ликвидации чрезвычайных ситуаций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010264230',0,'ЦСР_2016',1,'Субсидия федеральному государственному унитарному авиационному предприятию Министерства Российской Федерации по делам гражданской обороны, чрезвычайным ситуациям и ликвидации последствий стихийных бедствий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение повседневного функционирования подразделений МЧС России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010400000',0,'ЦСР_2016',1,'Основное мероприятие "Оснащение подразделений МЧС России современными образцами техники и оборудования в рамках государственного оборонного заказа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010500000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие инфраструктуры МЧС России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010600000',0,'ЦСР_2016',1,'Основное мероприятие "Организация и проведение противофонтанных работ на нефтяных и газовых скважинах"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010700000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие деятельности некоммерческих организаций, осуществляющих деятельность в области защиты населения и территорий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010760400',0,'ЦСР_2016',1,'Субсидии социально ориентированным некоммерческим организациям, осуществляющим деятельность в области защиты населения и территорий от чрезвычайных ситуаций, обеспечения пожарной безопасности и безопасности людей на водных объектах',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010800000',0,'ЦСР_2016',1,'Основное мероприятие "Снижение рисков и смягчение последствий чрезвычайных ситуаций природного и техногенного характера"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1010900000',0,'ЦСР_2016',1,'Основное мероприятие "Преодоление последствий радиационных аварий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1011000000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие системы обеспечения пожарной безопасности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1011100000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение устойчивости жилых домов, основных объектов и систем жизнеобеспечения в сейсмических районах Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1011200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие системы обеспечения вызова экстренных оперативных служб по единому номеру "112"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1020000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение и управление"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1020100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение повседневного функционирования подразделений центрального аппарата и территориальных подразделений МЧС России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1020200000',0,'ЦСР_2016',1,'Основное мероприятие "Научное обеспечение деятельности МЧС России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1020300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение жильем кадрового состава МЧС России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1020400000',0,'ЦСР_2016',1,'Основное мероприятие "Финансовое обеспечение реализации программ высшего профессионального образования в области защиты населения и территорий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1020500000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение международного сотрудничества в установленной сфере деятельности МЧС России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1020600000',0,'ЦСР_2016',1,'Основное мероприятие "Оценка рисков и минимизация недостижения целей и задач государственной программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1020700000',0,'ЦСР_2016',1,'Основное мероприятие "Финансовое обеспечение оказания медицинской, санаторно-курортной и реабилитационной помощи кадровому составу МЧС России, а также гражданам, подвергшимся радиационному воздействию"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1030000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие системы обеспечения промышленной безопасности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1030100000',0,'ЦСР_2016',1,'Основное мероприятие "Создание информационно-технологической инфраструктуры системы обеспечения промышленной безопасности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1030200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение проведения технологического надзора и федерального государственного надзора в области использования атомной энергии"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1030254890',0,'ЦСР_2016',1,'Субвенции бюджетам Республики Крым и города федерального значения Севастополя на осуществление части переданных полномочий Российской Федерации в сфере государственного контроля (надзора) в области промышленной безопасности, электроэнергетики и безоп',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1030300000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление международного сотрудничества в установленной сфере деятельности, направленного на совершенствование государственного регулирования технологической безопасности и безопасности при использовании атомной энергии в ми',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1030400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1060000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Пожарная безопасность в Российской Федерации на период до 2017 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1080000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Повышение устойчивости жилых домов, основных объектов и систем жизнеобеспечения в сейсмических районах Российской Федерации на 2009 - 2018 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1080051050',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий федеральной целевой программы "Повышение устойчивости жилых домов, основных объектов и систем жизнеобеспечения в сейсмических районах Российской Федерации на 2009 - 2018 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1090000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Создание системы обеспечения вызова экстренных оперативных служб по единому номеру "112" в Российской Федерации на 2013 - 2017 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1090050980',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий федеральной целевой программы "Создание системы обеспечения вызова экстренных оперативных служб по единому номеру "112" в Российской Федерации на 2013 - 2017 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '10Б0000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Национальная система химической и биологической безопасности Российской Федерации (2015 - 2020 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '10Г0000000',0,'ЦСР_2016',1,'Подпрограмма "Построение и развитие аппаратно-программного комплекса "Безопасный город"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '10Г0100000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-техническое, нормативно-правовое и организационно-методическое обеспечение реализации мероприятий по построению и развитию аппаратно-программного комплекса "Безопасный город"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '10Г0200000',0,'ЦСР_2016',1,'Основное мероприятие "Внедрение сегментов аппаратно-программного комплекса "Безопасный город" на муниципальном уровне и их интеграция в комплексную систему обеспечения безопасности жизнедеятельности населения субъекта Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1100000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие культуры и туризма" на 2013 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1110000000',0,'ЦСР_2016',1,'Подпрограмма "Наследие"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1110100000',0,'ЦСР_2016',1,'Основное мероприятие "Сохранение, использование, популяризация исторического и культурного наследия"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1110151450',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на мероприятия по реализации комплексного проекта "Культурное наследие - остров-град Свияжск и древний Болгар"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1110160850',0,'ЦСР_2016',1,'Субсидия Общероссийской общественно-государственной организации "Российское военно-историческое общество"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1110162320',0,'ЦСР_2016',1,'Субсидии Благотворительному фонду по восстановлению Воскресенского Ново-Иерусалимского ставропигиального мужского монастыря Русской Православной Церкви на воссоздание исторического облика монастыря',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1110200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие библиотечного дела"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1110251440',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на комплектование книжных фондов библиотек муниципальных образований и государственных библиотек городов Москвы и Санкт-Петербурга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1110251460',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на подключение общедоступных библиотек Российской Федерации к сети "Интернет" и развитие системы библиотечного дела с учетом задачи расширения информационных технологий и оцифровки',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1110300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие музейного дела"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1110400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие архивного дела"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120000000',0,'ЦСР_2016',1,'Подпрограмма "Искусство"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120100000',0,'ЦСР_2016',1,'Основное мероприятие "Сохранение и развитие исполнительских искусств"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120151490',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на реализацию мероприятий по созданию инновационных культурных центров',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120160160',0,'ЦСР_2016',1,'Субсидии на реализацию творческих проектов в сфере музыкального, театрального, изобразительного искусства и народного творчества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120200000',0,'ЦСР_2016',1,'Основное мероприятие "Сохранение и развитие кинематографии"',0,'',0,'','', '19000101',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 '1120300000',0,'ЦСР_2016',1,'Основное мероприятие "Сохранение и развитие традиционной народной культуры, нематериального культурного наследия народов Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120400000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка творческих инициатив населения, а также выдающихся деятелей, организаций в сфере культуры, творческих союзов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120430520',0,'ЦСР_2016',1,'Премии Правительства Российской Федерации в области культуры',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120430540',0,'ЦСР_2016',1,'Премии Правительства Российской Федерации "Душа России" за вклад в развитие народного творчества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120451470',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на государственную поддержку муниципальных учреждений культуры',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120451480',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на государственную поддержку лучших работников муниципальных учреждений культуры, находящихся на территориях сельских поселений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120451500',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на гранты в области науки, культуры, искусства и средств массовой информации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120451510',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на премии в области литературы и искусства, образования, печатных средств массовой информации, науки и техники и иные поощрения за особые заслуги перед государством',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120453940',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на оказание государственной поддержки (грантов) театрам и музыкальным организациям, находящимся в ведении субъектов Российской Федерации и муниципальных образований, для реализации творческих проектов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120462290',0,'ЦСР_2016',1,'Субсидии некоммерческим организациям на оказание государственной поддержки (грантов) независимым театральным и музыкальным коллективам для реализации творческих проектов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120462330',0,'ЦСР_2016',1,'Субсидии творческим союзам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120500000',0,'ЦСР_2016',1,'Основное мероприятие "Организация и проведение мероприятий, а также работ по строительству, реконструкции, реставрации, посвященных значимым событиям российской культуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120560170',0,'ЦСР_2016',1,'Субсидии на развитие гуманитарного сотрудничества между Российской Федерацией и Республикой Польша и поддержку российско-польского диалога',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1120560180',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий и творческих проектов в рамках развития международной культурной коммуникации Северо-Кавказского федерального округа',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1130000000',0,'ЦСР_2016',1,'Подпрограмма "Туризм"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1130100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие внутреннего туризма"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1130130290',0,'ЦСР_2016',1,'Премии Правительства Российской Федерации в области туризма',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1130200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие международного туризма"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1140000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение условий реализации государственной программы Российской Федерации "Развитие культуры и туризма" на 2013 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1140100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие инфраструктуры и системы управления в сфере культуры и туризма"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1140200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие фундаментальных и прикладных исследований в сфере культуры и туризма"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1150000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Культура России (2012 - 2018 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1150050140',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий федеральной целевой программы "Культура России (2012 - 2018 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1160000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие внутреннего и въездного туризма в Российской Федерации (2011 - 2018 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1160051100',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий федеральной целевой программы "Развитие внутреннего и въездного туризма в Российской Федерации (2011 - 2018 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1170000000',0,'ЦСР_2016',1,'Подпрограмма "Укрепление единства российской нации и этнокультурное развитие народов России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1170100000',0,'ЦСР_2016',1,'Основное мероприятие "Выработка и реализация государственной национальной политики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1170200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка экономического и социального развития коренных малочисленных народов Севера, Сибири и Дальнего Востока Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1170250910',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на поддержку экономического и социального развития коренных малочисленных народов Севера, Сибири и Дальнего Востока',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1180000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Укрепление единства российской нации и этнокультурное развитие народов России (2014 - 2020 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1180052360',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий федеральной целевой программы "Укрепление единства российской нации и этнокультурное развитие народов России (2014 - 2020 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1200000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Охрана окружающей среды" на 2012 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1210000000',0,'ЦСР_2016',1,'Подпрограмма "Регулирование качества окружающей среды"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1210100000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативно-правовое, методическое и информационно-аналитическое обеспечение регулирования в области охраны окружающей среды"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1210200000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение международных обязательств в области охраны окружающей среды"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1210300000',0,'ЦСР_2016',1,'Основное мероприятие "Организация и проведение комплексного государственного экологического надзора,  разрешительной и лицензионной деятельности в части ограничения негативного техногенного воздействия на окружающую среду и экологической экспертизы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1210354860',0,'ЦСР_2016',1,'Субвенции бюджетам Республики Крым и города федерального значения Севастополя на осуществление части переданных полномочий Российской Федерации в сфере охраны окружающей среды',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1220000000',0,'ЦСР_2016',1,'Подпрограмма "Биологическое разнообразие России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1220100000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативно-правовое, методическое и информационно-аналитическое обеспечение деятельности  в сфере сохранения и восстановления биологического разнообразия"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1220200000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение международных обязательств в сфере сохранения и восстановления биологического разнообразия"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1220300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение охраны объектов животного мира"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1220400000',0,'ЦСР_2016',1,'Основное мероприятие "Функционирование и развитие системы особо охраняемых природных территорий федерального значения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1230000000',0,'ЦСР_2016',1,'Подпрограмма "Гидрометеорология и мониторинг окружающей среды"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1230100000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативно-правовое, методическое и информационно-аналитическое обеспечение деятельности  в сфере гидрометеорологии и мониторинга окружающей среды"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1230200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие единой государственной системы экологического мониторинга"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1230300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение функционирования и развития государственной наблюдательной сети, государственной системы наблюдений, системы получения, сбора и распространения информации в области гидрометеорологии и смежных с ней областях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1230400000',0,'ЦСР_2016',1,'Основное мероприятие "Исследования и разработка методов и технологий в сфере гидрометеорологии и мониторинга окружающей среды"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1230500000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение выполнения государственных функций в сфере гидрометеорологии и мониторинга окружающей среды и смежных с ней областях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1230600000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение международных обязательств в сфере гидрометеорологии и мониторинга окружающей среды и иное международное сотрудничество"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1240000000',0,'ЦСР_2016',1,'Подпрограмма "Организация и обеспечение работ и научных исследований в Арктике и Антарктике"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1240100000',0,'ЦСР_2016',1,'Основное мероприятие "Организация и проведение комплексных исследований и работ в Арктике и Антарктике"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1240200000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативно-правовое обеспечение работ и научных исследований в Арктике и Антарктике"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1260000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Охрана озера Байкал и социально-экономическое развитие Байкальской природной территории на 2012 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1260050290',0,'ЦСР_2016',1,'Субсидии на  мероприятия федеральной целевой программы "Охрана озера Байкал и социально-экономическое развитие Байкальской природной территории на 2012 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1270000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Создание и развитие системы мониторинга геофизической обстановки над территорией Российской Федерации на 2008 - 2016  годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1280000000',0,'ЦСР_2016',1,'Подпрограмма "Ликвидация накопленного экологического ущерба"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1280100000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативно-правовое обеспечение в сфере ликвидации накопленного экологического ущерба"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1280200000',0,'ЦСР_2016',1,'Основное мероприятие "Подготовка и реализация проектов по ликвидации накопленных загрязнений бывших промышленных производств"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1280300000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка региональных проектов в области обращения с отходами и ликвидации накопленного экологического ущерба"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1280355070',0,'ЦСР_2016',1,'Субсидии на поддержку региональных проектов в области обращения с отходами и ликвидации накопленного экологического ущерба',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1280400000',0,'ЦСР_2016',1,'Основное мероприятие "Ликвидация последствий загрязнения и иного негативного воздействия на окружающую среду в результате экономической деятельности на особо охраняемых природных территориях федерального значения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1280500000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-методическое и аналитическое сопровождение, мониторинг и оценка реализации проектов по ликвидации накопленного экологического ущерба"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1280600000',0,'ЦСР_2016',1,'Основное мероприятие "Ликвидация экологических и иных последствий ведения горных работ на ликвидируемых организациях угольной промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1300000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие физической культуры и спорта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1310000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие физической культуры и массового спорта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1310100000',0,'ЦСР_2016',1,'Основное мероприятие "Физическое воспитание и обеспечение организации и проведения физкультурных мероприятий и массовых спортивных мероприятий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1310151650',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на премирование регионов - победителей фестиваля "Кавказские игры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1310160230',0,'ЦСР_2016',1,'Субсидия на финансовое обеспечение подготовки и участия инвалидов с умственной отсталостью в физкультурных мероприятиях',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1310160240',0,'ЦСР_2016',1,'Субсидии на финансовое обеспечение мероприятий, направленных на развитие служебно-прикладных видов спорта, совершенствование физической подготовки сотрудников правоохранительных органов и органов безопасности и поддержку массового физкультурно-спорти',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1310200000',0,'ЦСР_2016',1,'Основное мероприятие "Вовлечение населения в занятия физической культурой и массовым спортом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1310300000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование спортивной инфраструктуры и материально-технической базы для занятий физической культурой и массовым спортом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1310400000',0,'ЦСР_2016',1,'Основное мероприятие "Внедрение и реализация Всероссийского физкультурно-спортивного комплекса "Готов к труду и обороне"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1310451270',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий по поэтапному внедрению Всероссийского физкультурно-спортивного комплекса "Готов к труду и обороне" (ГТО)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1310500000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие студенческого спорта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1310600000',0,'ЦСР_2016',1,'Основное мероприятие "Организация и проведение научно-исследовательских и опытно-конструкторских работ в сфере физической культуры и массового спорта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие спорта высших достижений и системы подготовки спортивного резерва"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320100000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение спортивных мероприятий, обеспечение подготовки спортсменов высокого класса, материально-техническое обеспечение спортивных сборных команд Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320130440',0,'ЦСР_2016',1,'Стипендии Президента Российской Федерации спортсменам, тренерам и иным специалистам спортивных сборных команд Российской Федерации по видам спорта, включенным в программы Олимпийских игр, Паралимпийских игр и Сурдлимпийских игр, чемпионам Олимпийских',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320160190',0,'ЦСР_2016',1,'Субсидии Общероссийской общественной организации "Паралимпийский комитет России", Общероссийскому союзу физкультурно-спортивных общественных объединений инвалидов "Сурдлимпийский комитет России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320160250',0,'ЦСР_2016',1,'Субсидии на реализацию выполнения задач и программ развития футбола на территории Республики Крым и города федерального значения Севастополя',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320160540',0,'ЦСР_2016',1,'Субсидии Фонду "Талант и успех", г. Сочи, Краснодарский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие системы подготовки спортивного резерва"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320250810',0,'ЦСР_2016',1,'Субсидии на адресную финансовую поддержку спортивных организаций, осуществляющих подготовку спортивного резерва для сборных команд Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320252150',0,'ЦСР_2016',1,'Субсидии бюджетам Республики Крым и города федерального значения Севастополя на адресную финансовую поддержку спортивных организаций, осуществляющих подготовку спортивного резерва для сборных команд Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320300000',0,'ЦСР_2016',1,'Основное мероприятие "Антидопинговое обеспечение спортивных сборных команд Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320360150',0,'ЦСР_2016',1,'Субсидия на финансовое обеспечение мероприятий в части антидопингового обеспечения спортивных сборных команд Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320400000',0,'ЦСР_2016',1,'Основное мероприятие "Подготовка и проведение особо значимых международных спортивных мероприятий,  проводимых на территории Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320455010',0,'ЦСР_2016',1,'Субсидия бюджету Красноярского края на софинансирование строительства объектов капитального строительства, необходимых для подготовки и проведения XXIX Всемирной зимней универсиады 2019 года в г. Красноярске',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320460600',0,'ЦСР_2016',1,'Субсидия автономной некоммерческой организации "Исполнительная дирекция XXIX Всемирной зимней универсиады 2019 года в г. Красноярске"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320500000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-методическое и информационно-аналитическое обеспечение подготовки спортсменов высокого класса, спортивных сборных команд Российской Федерации и спортивного резерва"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1320600000',0,'ЦСР_2016',1,'Основное мероприятие "Организация и проведение научно-исследовательских и опытно-конструкторских работ в сфере спорта высших достижений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1330000000',0,'ЦСР_2016',1,'Подпрограмма "Подготовка и проведение Чемпионата мира по футболу ФИФА 2018 года и Кубка конфедераций ФИФА 2017 года в Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1330100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение нормативно-правовых основ в целях подготовки и проведения Чемпионата мира по футболу ФИФА 2018 года и Кубка конфедераций 2017 года и реализации гарантий, взятых Правительством Российской Федерации перед ФИФА"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1330200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие спортивной инфраструктуры для проведения Чемпионата мира по футболу ФИФА 2018 года и Кубка конфедераций ФИФА 2017 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1330251540',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на реализацию мероприятий по подготовке и проведению чемпионата мира по футболу в 2018 году в Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1330268250',0,'ЦСР_2016',1,'Субсидия федеральному государственному унитарному предприятию "Спорт-Инжиниринг" на осуществление функций застройщика по строительству и реконструкции стадионов для подготовки и проведения чемпионата мира по футболу ФИФА 2018 года',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1330300000',0,'ЦСР_2016',1,'Основное мероприятие "Организация подготовки и проведения Чемпионата мира по футболу ФИФА 2018 года и Кубка конфедераций ФИФА 2017 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1340000000',0,'ЦСР_2016',1,'Подпрограмма "Управление развитием отрасли физической культуры и спорта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1340100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование нормативно-правовой базы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1340200000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация государственной политики в сфере физической культуры и спорта"',0,'',0,'','', '19000101',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 '1340300000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение в Российской Федерации семинаров, конференций, форумов, конвенций в сфере физической культуры и спорта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1340400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие международного спортивного сотрудничества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1340460260',0,'ЦСР_2016',1,'Субсидии на финансовое обеспечение  мероприятий, направленных на подготовку и проведение Международного спортивного форума "Россия - спортивная держава"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1340500000',0,'ЦСР_2016',1,'Основное мероприятие "Внедрение современных информационно-коммуникационных технологий в сферу физической культуры и спорта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1360000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие физической культуры и спорта в Российской Федерации на 2016 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1360054950',0,'ЦСР_2016',1,'Субсидии на финансовое обеспечение мероприятий федеральной целевой программы "Развитие физической культуры и спорта в Российской Федерации на 2016 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1400000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие науки и технологий" на 2013 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1410000000',0,'ЦСР_2016',1,'Подпрограмма "Фундаментальные научные исследования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1410100000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение фундаментальных научных исследований учреждениями государственных академий наук, финансовое обеспечение государственных академий наук"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1410200000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение фундаментальных научных исследований по приоритетным направлениям, определяемым Российской академией наук"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1410300000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение фундаментальных научных исследований государственными учреждениями, не являющимися учреждениями государственных академий наук"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1410400000',0,'ЦСР_2016',1,'Основное мероприятие "Грантовое финансирование фундаментальных научных исследований Российским гуманитарным научным фондом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1410500000',0,'ЦСР_2016',1,'Основное мероприятие "Грантовое финансирование фундаментальных научных исследований Российским фондом фундаментальных исследований"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1410600000',0,'ЦСР_2016',1,'Основное мероприятие "Грантовое финансирование фундаментальных научных исследований Российским научным фондом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1410665900',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в Российский научный фонд',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1410700000',0,'ЦСР_2016',1,'Основное мероприятие "Гранты Президента Российской Федерации и Правительства Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1410800000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие кадрового потенциала в научных учреждениях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1420000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие сектора прикладных научных исследований и разработок"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1420100000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение прикладных научных исследований НИЦ "Курчатовский институт" и другими государственными учреждениями, не подведомственными Минобрнауки России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1420200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение деятельности подведомственных учреждений Минобрнауки России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430000000',0,'ЦСР_2016',1,'Подпрограмма "Институциональное развитие научно-исследовательского сектора"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430100000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка развития научной кооперации образовательных организаций высшего образования, государственных научных организаций с предприятиями высокотехнологичных секторов экономики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430164820',0,'ЦСР_2016',1,'Субсидии на государственную поддержку развития кооперации российских образовательных организаций высшего образования, государственных научных учреждений и организаций, реализующих комплексные проекты по созданию высокотехнологичного производства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430200000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка научных исследований, проводимых под руководством ведущих ученых в образовательных организациях высшего образования, научных организациях Федерального агентства научных организаций и государственных научных центрах"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430261460',0,'ЦСР_2016',1,'Субсидии на предоставление грантов Правительства Российской Федерации, выделяемых для государственной поддержки научных исследований, проводимых под руководством ведущих ученых в российских образовательных организациях высшего образования, научных уч',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430300000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы оплаты труда научных работников"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие и поддержка социальной, инженерной и инновационной инфраструктуры наукоградов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430451580',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на развитие и поддержку социальной, инженерной и инновационной инфраструктуры наукоградов Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430500000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация на территории Российской Федерации проектов создания крупных научных установок класса мега-сайенс"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430600000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение выплаты государственных премий Российской Федерации, премий Правительства Российской Федерации, иных премий и выплат в области науки и техники, стипендий Президента Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430630460',0,'ЦСР_2016',1,'Стипендия Президента Российской Федерации для молодых ученых и аспирантов, осуществляющих перспективные научные исследования и разработки по приоритетным направлениям модернизации российской экономики',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430630480',0,'ЦСР_2016',1,'Премии Правительства Российской Федерации в области науки и техники ученым и специалистам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430630500',0,'ЦСР_2016',1,'Премии Правительства Российской Федерации в области науки и техники для молодых ученых',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1430700000',0,'ЦСР_2016',1,'Основное мероприятие "Управленческое, информационно-аналитическое, организационно-техническое обеспечение и мониторинг реализации мероприятий Государственной программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1450000000',0,'ЦСР_2016',1,'Подпрограмма "Международное сотрудничество в сфере науки"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1450100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации соглашений с правительствами иностранных государств и международными организациями в части обеспечения научно-исследовательской деятельности ученых за рубежом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1450200000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение финансовых обязательств Российской Федерации в рамках соглашения стран Евразийского экономического сообщества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1450300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение уплаты взносов Российской Федерации в международные научные организации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1450400000',0,'ЦСР_2016',1,'Основное мероприятие "Участие Российской Федерации в крупных научно-исследовательских проектах"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1450464630',0,'ЦСР_2016',1,'Субсидии открытому акционерному обществу "РОСНАНО" на возмещение расходов по оплате целевого взноса на строительство установки Европейского рентгеновского лазера на свободных электронах',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1470000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Исследования и разработки по приоритетным направлениям развития научно-технологического комплекса России на 2014 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1490000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Мировой океан" на 2016 - 2031 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1490100000',0,'ЦСР_2016',1,'Подпрограмма "Комплексные исследования Антарктики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1490200000',0,'ЦСР_2016',1,'Подпрограмма "Экспедиционные исследования в Мировом океане"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1490300000',0,'ЦСР_2016',1,'Подпрограмма "Прикладные исследования природы Мирового океана"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1490400000',0,'ЦСР_2016',1,'Подпрограмма "Совершенствование информационного обеспечения морской деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1500000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Экономическое развитие и инновационная экономика"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510000000',0,'ЦСР_2016',1,'Подпрограмма "Инвестиционный климат"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510100000',0,'ЦСР_2016',1,'Основное мероприятие "Создание благоприятных условий для привлечения инвестиций в экономику Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510200000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование корпоративного управления"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510300000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение качества оценки регулирующего воздействия нормативных правовых актов и их проектов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие особых экономических зон"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510463940',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Особые экономические зоны"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510467350',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Особые экономические зоны", г. Москва, для участия в проекте создания особой экономической зоны промышленно-производственного типа в городе Владивостоке',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510500000',0,'ЦСР_2016',1,'Основное мероприятие "Создание благоприятной конкурентной среды"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510600000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование контроля за применением антимонопольного законодательства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510700000',0,'ЦСР_2016',1,'Основное мероприятие "Создание условий для эффективной реализации государственной политики в области контроля иностранных инвестиций в хозяйственные общества, имеющие стратегическое значение"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510800000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование и развитие  контрактной системы в сфере закупок"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510900000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие развитию моногородов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1510962300',0,'ЦСР_2016',1,'Субсидии некоммерческой организации "Фонд развития моногородов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1520000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие малого и среднего предпринимательства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1520100000',0,'ЦСР_2016',1,'Основное мероприятие "Федеральная финансовая программа поддержки малого и среднего предпринимательства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1520150640',0,'ЦСР_2016',1,'Субсидии на государственную поддержку малого и среднего предпринимательства, включая крестьянские (фермерские) хозяйства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1520200000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование нормативно-правового регулирования малого и среднего предпринимательства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1520300000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование национальной системы гарантийных организаций для субъектов малого и среднего предпринимательства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1520400000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие развитию молодежного предпринимательства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1520454450',0,'ЦСР_2016',1,'Субсидии на государственную поддержку молодежного предпринимательства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1530000000',0,'ЦСР_2016',1,'Подпрограмма "Государственная регистрация прав, кадастр и картография"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1530100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение государственного кадастрового учета, государственной регистрации прав и картографии"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1530154710',0,'ЦСР_2016',1,'Субвенции бюджетам Республики Крым и города федерального значения Севастополя на осуществление части переданных полномочий Российской Федерации в сфере государственной регистрации прав на недвижимое имущество и сделок с ним, государственного кадастро',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1530200000',0,'ЦСР_2016',1,'Основное мероприятие "Землеустройство и мониторинг состояния и использования земельных ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1530300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие инфраструктуры пространственных данных Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1530400000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование нормативно-правового регулирования в сфере реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1540000000',0,'ЦСР_2016',1,'Подпрограмма "Совершенствование системы государственного управления"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1540100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование предоставления государственных услуг и исполнения государственных функций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1540200000',0,'ЦСР_2016',1,'Основное мероприятие "Улучшение регуляторной среды"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1540300000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование единой национальной системы аккредитации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1550000000',0,'ЦСР_2016',1,'Подпрограмма "Стимулирование инноваций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1550100000',0,'ЦСР_2016',1,'Основное мероприятие "Стимулирование спроса на инновации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1550200000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка малого инновационного предпринимательства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1550300000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка регионов - инновационных лидеров"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1550400000',0,'ЦСР_2016',1,'Основное мероприятие "Создание университетского комплекса в территориально обособленном инновационном центре "Иннополис"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1550500000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение исследований в целях инновационного развития экономики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1550600000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие механизмов правовой охраны и защиты интеллектуальной собственности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1550700000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие развитию современной инновационной инфраструктуры в сфере нанотехнологий, механизмов и инструментов для реализации потенциала наноиндустрии"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1560000000',0,'ЦСР_2016',1,'Подпрограмма "Регулирование инфраструктурных отраслей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1560100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственное регулирование, включая ценовое (тарифное) регулирование и поведенческие стандарты и правила"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1560200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственный контроль, досудебное урегулирование споров и рассмотрение разногласий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1560300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие институциональной среды регулирования, включая совершенствование нормативной правовой базы, системы регулирования, единой среды электронного регулирования, международного сотрудничества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1570000000',0,'ЦСР_2016',1,'Подпрограмма "Управленческие кадры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1570100000',0,'ЦСР_2016',1,'Основное мероприятие "Подготовка управленческих кадров для организаций народного хозяйства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1570150660',0,'ЦСР_2016',1,'Субсидии на подготовку управленческих кадров для организаций народного хозяйства Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1570200000',0,'ЦСР_2016',1,'Основное мероприятие "Организация и проведение обучения по дополнительным профессиональным программам за рубежом, в том числе в рамках взаимных обменов с иностранными государствами на основе конкурсного отбора проектов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1570300000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение качества и информационно-технологического обеспечения образовательных программ и контроль качества подготовки специалистов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1570400000',0,'ЦСР_2016',1,'Основное мероприятие "Подготовка управленческих кадров в сфере здравоохранения, образования и культуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1580000000',0,'ЦСР_2016',1,'Подпрограмма "Совершенствование системы государственного стратегического управления"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1580100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие государственного стратегического планирования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1580200000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка прогнозов социально-экономического развития Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1580300000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация механизмов стратегического управления социально-экономическим развитием субъектов Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1580400000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка предложений по совершенствованию и участие в реализации государственной политики в отдельных секторах экономики"',0,'',0,'','', '19000101',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 '1580500000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка предложений по совершенствованию и участие в реализации государственной политики в социальной сфере"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1580600000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование расходов инвестиционного характера, формирование и реализация федеральной адресной инвестиционной программы на очередной год и плановый период"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1580700000',0,'ЦСР_2016',1,'Основное мероприятие "Создание условий для эффективной разработки и реализации федеральных целевых программ и целевых программ ведомств"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1580800000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-аналитическое обеспечение развития стратегического планирования и прогнозирования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1590000000',0,'ЦСР_2016',1,'Подпрограмма "Официальная статистика"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1590100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение выполнения комплекса работ по реализации Федерального плана статистических работ"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1590200000',0,'ЦСР_2016',1,'Основное мероприятие "Подготовка, проведение и подведение итогов всероссийских переписей населения (микропереписей)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1590300000',0,'ЦСР_2016',1,'Основное мероприятие "Подготовка, проведение и подведение итогов всероссийских сельскохозяйственных переписей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1590353910',0,'ЦСР_2016',1,'Субвенции на проведение Всероссийской сельскохозяйственной переписи в 2016 году',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1590400000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка базовых таблиц "затраты - выпуск" и подготовка, проведение и подведение итогов сплошного федерального статистического наблюдения за деятельностью субъектов малого и среднего предпринимательства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1590500000',0,'ЦСР_2016',1,'Основное мероприятие "Организация системы федеральных статистических наблюдений по социально-демографическим проблемам и мониторинга  экономических потерь от смертности, заболеваемости и инвалидизации населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1590600000',0,'ЦСР_2016',1,'Основное мероприятие "Организация и проведение  выборочных обследований отдельных аспектов занятости населения и оплаты труда"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1590700000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие системы государственной статистики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '15Б0000000',0,'ЦСР_2016',1,'Подпрограмма "Создание и развитие инновационного центра "Сколково"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '15Б0100000',0,'ЦСР_2016',1,'Основное мероприятие "Создание и развитие инновационной среды"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '15Б0162190',0,'ЦСР_2016',1,'Субсидии некоммерческой организации Фонд развития Центра разработки и коммерциализации новых технологий на компенсацию затрат участников проекта создания инновационного центра "Сколково" по уплате таможенных платежей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '15Б0200000',0,'ЦСР_2016',1,'Основное мероприятие "Создание и развитие Сколковского института науки и технологий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '15Б0300000',0,'ЦСР_2016',1,'Основное мероприятие "Создание и управление физической инфраструктурой инновационного центра "Сколково"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '15Г0000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие единой государственной системы регистрации прав и кадастрового учета недвижимости  (2014 - 2019 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '15Г0054150',0,'ЦСР_2016',1,'Субсидии на реализацию в Крымском федеральном округе мероприятий федеральной целевой программы "Развитие единой государственной системы регистрации прав и кадастрового учета недвижимости (2014 - 2019 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1600000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие промышленности и повышение ее конкурентоспособности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие транспортного и специального машиностроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие автомобилестроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610164660',0,'ЦСР_2016',1,'Субсидии организациям автомобилестроения на перевозку автомобилей, произведенных на территории Дальневосточного федерального округа, в другие регионы страны',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610164980',0,'ЦСР_2016',1,'Субсидии на возмещение части затрат организациям и индивидуальным предпринимателям, осуществляющим деятельность по обращению с отходами, образовавшимися в результате утраты колесными транспортными средствами (шасси), в отношении которых уплачен утили',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610165200',0,'ЦСР_2016',1,'Субсидии российским кредитным организациям на возмещение выпадающих доходов по кредитам, выданным российскими кредитными организациями в 2013 - 2014 годах физическим лицам на приобретение автомобилей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610166730',0,'ЦСР_2016',1,'Субсидии российским производителям колесных транспортных средств на компенсацию части затрат на содержание рабочих мест',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610166750',0,'ЦСР_2016',1,'Субсидии российским производителям колесных транспортных средств на компенсацию части затрат, связанных с выпуском и поддержкой гарантийных обязательств по колесным транспортным средствам, соответствующим нормам Евро-4, Евро-5',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610166760',0,'ЦСР_2016',1,'Субсидии российским производителям колесных транспортных средств на компенсацию части затрат на использование энергоресурсов энергоемкими предприятиями автомобильной промышленности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610168330',0,'ЦСР_2016',1,'Субсидии производителям колесных транспортных средств и самоходной техники на поддержание и развитие производственной базы в интересах обеспечения национальной обороны',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610168730',0,'ЦСР_2016',1,'Субсидии российским организациям автомобилестроения, реализующим инвестиционные проекты по производству колесных транспортных средств, их узлов и агрегатов, в том числе, по созданию (локализации) производства автомобильных двигателей, в г. Владивосто',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610168770',0,'ЦСР_2016',1,'Субсидии российским производителям грузовых колесных транспортных средств на возмещение части затрат на выплату купонного дохода по облигациям размещенным и (или) уплату процентов по кредитам, привлеченным на цели развития заготовительных производств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610168780',0,'ЦСР_2016',1,'Субсидии российским производителям  колесных транспортных средств на компенсацию части затрат, связанных с созданием и организацией производства транспортных средств с дистанционным и автономным управлением',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610168790',0,'ЦСР_2016',1,'Субсидии российским организациям автомобилестроения, в том числе их дочерним организациям, на возмещение части затрат на уплату процентов по кредитам, полученным на реализацию инвестиционных и инновационных проектов и (или) выплату купонного дохода п',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие транспортного машиностроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610263960',0,'ЦСР_2016',1,'Субсидии на возмещение потерь в доходах российских лизинговых организаций при предоставлении скидки при условии приобретения инновационных вагонов с повышенной осевой нагрузкой, а также на возмещение части затрат российским организациям на уплату про',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие сельскохозяйственного машиностроения, машиностроения для пищевой и перерабатывающей промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610368740',0,'ЦСР_2016',1,'Субсидии российским производителям самоходной и прицепной техники на компенсацию части затрат на содержание рабочих мест',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610368750',0,'ЦСР_2016',1,'Субсидии российским производителям самоходной и прицепной техники на компенсацию части затрат на использование энергоресурсов энергоемкими предприятиями',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610368760',0,'ЦСР_2016',1,'Субсидии российским производителям на компенсацию части затрат, связанных с выпуском и поддержкой гарантийных обязательств в отношении высокопроизводительной самоходной и прицепной техники',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие машиностроения специализированных производств (строительно-дорожная и коммунальная техника, пожарная, аэродромная, лесная техника)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610468740',0,'ЦСР_2016',1,'Субсидии российским производителям самоходной и прицепной техники на компенсацию части затрат на содержание рабочих мест',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610468750',0,'ЦСР_2016',1,'Субсидии российским производителям самоходной и прицепной техники на компенсацию части затрат на использование энергоресурсов энергоемкими предприятиями',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610468760',0,'ЦСР_2016',1,'Субсидии российским производителям на компенсацию части затрат, связанных с выпуском и поддержкой гарантийных обязательств в отношении высокопроизводительной самоходной и прицепной техники',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610500000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка организаций транспортного и специального машиностроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1610564710',0,'ЦСР_2016',1,'Субсидии российским организациям транспортного машиностроения на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономической деятельности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1620000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие производства средств производства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1620100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие станкоинструментальной промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1620166720',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в Государственную корпорацию по содействию разработке, производству и экспорту высокотехнологичной промышленной продукции "Ростех" на цели реализации проектов по созданию серийных производств станкоинструмента',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1620168480',0,'ЦСР_2016',1,'Субсидии российским организациям на компенсацию части затрат на проведение научно-исследовательских и опытно-конструкторских работ в рамках реализации комплексных проектов по организации серийных производств станкоинструментальной продукции',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1620200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие тяжелого машиностроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1620300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие промышленности силовой электротехники и энергетического машиностроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1620400000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка отечественного инженерного программного обеспечения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1620500000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие робототехники, цифрового производства и аддитивных технологий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1630000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие легкой и текстильной промышленности, народных художественных промыслов, индустрии детских товаров"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1630100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие легкой и текстильной промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1630164650',0,'ЦСР_2016',1,'Субсидии организациям легкой и текстильной промышленности на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях в 2006 - 2012 годах, на осуществление технического перевооружения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1630167190',0,'ЦСР_2016',1,'Субсидии организациям легкой и текстильной промышленности на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях в 2013 - 2015 годах, на реализацию новых инвестиционных проектов по техническому пере',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1630168670',0,'ЦСР_2016',1,'Субсидии организациям легкой промышленности на возмещение части затрат на обслуживание кредитов, привлеченных в российских кредитных организациях в 2012 - 2016 годах, на цели формирования межсезонных запасов, необходимых для производства товаров легк',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1630200000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка производства и реализации изделий народных художественных промыслов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1630264620',0,'ЦСР_2016',1,'Субсидии организациям народных художественных промыслов на поддержку производства и реализации изделий народных художественных промыслов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1630300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие индустрии детских товаров"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1630362480',0,'ЦСР_2016',1,'Субсидии российским управляющим организациям индустриальных парков индустрии детских товаров на возмещение части затрат на создание и (или) развитие имущественного комплекса, в том числе инфраструктуры индустриальных парков индустрии детских товаров',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1630362500',0,'ЦСР_2016',1,'Субсидии российским организациям на компенсацию части затрат на проведение научно-исследовательских и опытно-конструкторских работ в рамках реализации комплексных инвестиционных проектов индустрии детских товаров',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1630364840',0,'ЦСР_2016',1,'Субсидии российским организациям на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях в 2013 - 2016 годах, на реализацию приоритетных инвестиционных проектов индустрии детских товаров, а также на',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1630400000',0,'ЦСР_2016',1,'Основное мероприятие "Противодействие теневому производству и несанкционированному импорту продукции текстильной и легкой промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1640000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие производства традиционных и новых материалов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1640100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие металлургии и промышленности редких и редкоземельных металлов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1640168370',0,'ЦСР_2016',1,'Субсидии российским организациям на компенсацию части затрат на захоронение радиоактивных отходов (обращение с радиоактивными отходами)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1640200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие предприятий лесопромышленного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1640268210',0,'ЦСР_2016',1,'Субсидии организациям лесопромышленного комплекса на возмещение части затрат на обслуживание кредитов, полученных в российских кредитных организациях в 2011 - 2015 годах на цели формирования сезонных запасов сырья, материалов и топлива',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1640268220',0,'ЦСР_2016',1,'Субсидии организациям лесопромышленного комплекса на возмещение части затрат на обслуживание кредитов, привлеченных в 2012 - 2015 годах, на цели реализации инвестиционных проектов создания новых высокотехнологичных обрабатывающих производств по компл',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1640268690',0,'ЦСР_2016',1,'Субсидии российским лесоперерабатывающим предприятиям Дальневосточного федерального округа, участвующим в реализации приоритетных инвестиционных проектов в области освоения лесов, на возмещение части затрат, осуществленных в 2013 - 2015 годах на реал',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1640300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие химического комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1640368400',0,'ЦСР_2016',1,'Субсидии российским предприятиям (организациям) химического комплекса на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономической деяте',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1640400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие производства композиционных материалов (композитов) и изделий из них"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1640468430',0,'ЦСР_2016',1,'Субсидии на поддержку развития производства композиционных материалов (композитов) и изделий из них в рамках реализации российскими организациями комплексных инновационных проектов по созданию высокотехнологичной продукции',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1640500000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие промышленных биотехнологий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1650000000',0,'ЦСР_2016',1,'Подпрограмма "Содействие в реализации инвестиционных проектов и поддержка производителей высокотехнологической продукции в гражданских отраслях промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1650100000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация приоритетных инвестиционных проектов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1650168000',0,'ЦСР_2016',1,'Субсидии российским организациям на компенсацию части затрат на реализацию пилотных проектов в области инжиниринга и промышленного дизайна',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1650168350',0,'ЦСР_2016',1,'Субсидии российским организациям на компенсацию части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях в 2014 - 2016 годах на реализацию новых комплексных инвестиционных проектов по приоритетным направлениям граж',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1650200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение деятельности Фонда развития промышленности в целях поддержки реализации инвестиционных проектов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1650300000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка проектов по производству конкурентоспособной на внешних рынках высокотехнологичной промышленной продукции"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1650365110',0,'ЦСР_2016',1,'Имущественный взнос в государственную корпорацию "Банк развития и внешнеэкономической деятельности (Внешэкономбанк)" на возмещение части затрат, связанных с поддержкой производства высокотехнологичной продукции',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1660000000',0,'ЦСР_2016',1,'Подпрограмма "Содействие проведению научных исследований и опытных разработок в гражданских отраслях промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1660100000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка научно-исследовательских и опытно-конструкторских работ в гражданских отраслях промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1660160280',0,'ЦСР_2016',1,'Субсидии российским организациям на возмещение части затрат, связанных с уплатой пошлин при патентовании российских разработок производителей и экспортеров за рубежом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1660164110',0,'ЦСР_2016',1,'Субсидии российским операторам услуг на возмещение части затрат на приобретение специализированного инжинирингового программного обеспечения с целью повышения доступности специализированного инжинирингового программного обеспечения для конечных польз',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1660168460',0,'ЦСР_2016',1,'Субсидии российским организациям на компенсацию части затрат на проведение научно-исследовательских и опытно-конструкторских работ по приоритетным направлениям гражданской промышленности в рамках реализации такими организациями комплексных инвестицио',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1660200000',0,'ЦСР_2016',1,'Основное мероприятие "Научные исследования и сопровождение приоритетных и инновационных проектов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1660300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие научно-технологической инфраструктуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1660400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие технологий и промышленного потенциала фотоники"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1660500000',0,'ЦСР_2016',1,'Основное мероприятие "Сопровождение реализации научно-технической политики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1670000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие промышленной инфраструктуры  и инфраструктуры поддержки деятельности в сфере промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1670100000',0,'ЦСР_2016',1,'Основное мероприятие "Стимулирование создания и выведения на проектную мощность индустриальных (промышленных) парков, технопарков, промышленных кластеров"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1670154770',0,'ЦСР_2016',1,'Субсидии на возмещение затрат по созданию инфраструктуры индустриальных парков или технопарков, за исключением технопарков в сфере высоких технологий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1670160670',0,'ЦСР_2016',1,'Субсидии российским организациям - управляющим компаниям индустриальных (промышленных) парков и (или) технопарков на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и государственной корпорации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1670168640',0,'ЦСР_2016',1,'Субсидии участникам промышленных кластеров на возмещение части затрат при реализации совместных проектов по производству промышленной продукции кластера в целях импортозамещения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1670200000',0,'ЦСР_2016',1,'Основное мероприятие "Сопровождение развития инфраструктуры поддержки деятельности в сфере промышленности и промышленной инфраструктуры"',0,'',0,'','', '19000101',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 '1670254870',0,'ЦСР_2016',1,'Субсидии на софинансирование расходов по возмещению части затрат на реализацию инвестиционных проектов по модернизации и развитию промышленных предприятий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1670260660',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "Российская система качества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '16Д0000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие системы технического регулирования, стандартизации и обеспечение единства измерений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '16Д0100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие системы технического регулирования и стандартизации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '16Д0164600',0,'ЦСР_2016',1,'Субсидии организациям на создание и ведение Федерального информационного фонда технических регламентов и стандартов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '16Д0167400',0,'ЦСР_2016',1,'Субсидии на разработку международных, региональных и национальных документов в области стандартизации, обеспечивающих применение и исполнение требований технических регламентов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '16Д0200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение единства измерений и развитие эталонной базы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '16Д0264610',0,'ЦСР_2016',1,'Субсидии организациям на осуществление расходов в области обеспечения единства измерений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '16Д0300000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение научно-исследовательских и опытно-конструкторских работ в области технического регулирования, стандартизации, обеспечения единства измерений, информации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '16Д0400000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение научных исследований в области метрологии, а также разработка государственных (в том числе первичных) эталонов единиц величин"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '16Д0500000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка и утверждение отраслевых справочников наилучших доступных технологий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '16Д0600000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение деятельности Росстандарта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '16Ч0000000',0,'ЦСР_2016',1,'Президентская программа "Уничтожение запасов химического оружия в Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1700000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие авиационной промышленности на 2013 - 2025 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1710000000',0,'ЦСР_2016',1,'Подпрограмма "Самолетостроение"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1710100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка российских организаций самолетостроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1710164680',0,'ЦСР_2016',1,'Субсидии организациям авиационной промышленности, осуществляющим деятельность в области самолетостроения, на компенсацию затрат на уплату купонного дохода по облигационным займам, привлеченным с предоставлением в 2010 году государственных гарантий Ро',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1710164740',0,'ЦСР_2016',1,'Субсидии российским лизинговым компаниям на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономической деятельности (Внешэкономбанк)" в 2',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1710166630',0,'ЦСР_2016',1,'Взнос в уставный капитал публичного акционерного общества "Объединенная авиастроительная корпорация", г. Москва, в целях последующего взноса в уставный капитал специализированной компании - дочернего общества в целях реализации механизма гарантии ост',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1710167140',0,'ЦСР_2016',1,'Субсидии российским производителям авиационной техники в целях финансового обеспечения затрат по реализации проекта производства самолетов региональной авиации пассажировместимостью до 19 мест',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1710167420',0,'ЦСР_2016',1,'Субсидии изготовителям воздушных судов на возмещение части затрат на формирование первоначального склада запасных частей покупателей воздушных судов, обеспечение средствами наземного обслуживания, переподготовку авиационного персонала для воздушных с',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1710167680',0,'ЦСР_2016',1,'Субсидии российским компаниям на компенсацию части затрат на реализацию проектов по созданию сети авиационных сервисных центров, оказывающих поддержку по системе 24/365 на глобальном уровне',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1710167750',0,'ЦСР_2016',1,'Субсидии компаниям - производителям воздушных судов для местных и региональных воздушных линий на компенсацию части затрат на сертификацию таких воздушных судов, а также на компенсацию части затрат на реализацию проектов по подготовке и сертификации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1710200000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение научно-исследовательских и опытно-конструкторских работ в области самолетостроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1720000000',0,'ЦСР_2016',1,'Подпрограмма "Вертолетостроение"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1720100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка российских организаций вертолетостроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1720200000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение научно-исследовательских и опытно-конструкторских работ в области вертолетостроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1730000000',0,'ЦСР_2016',1,'Подпрограмма "Авиационное двигателестроение"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1730100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка российских организаций отрасли авиационного двигателестроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1730160920',0,'ЦСР_2016',1,'Субсидии организациям авиационной промышленности, осуществляющим деятельность в области двигателестроения, на возмещение затрат на уплату купонного дохода по облигационным займам, привлеченным в 2015 - 2016 годах с предоставлением государственных гар',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1730167630',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в Государственную корпорацию по содействию разработке, производству и экспорту высокотехнологичной промышленной продукции "Ростех" в целях финансирования расходов акционерного общества "Объединенная промышленн',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1730167660',0,'ЦСР_2016',1,'Субсидии российским организациям авиационной промышленности, осуществляющим деятельность в области авиационного двигателестроения, на компенсацию процентов по долгосрочным кредитам, полученным в российских кредитных организациях и в государственной к',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1730200000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение научно-исследовательских и опытно-конструкторских работ в области авиационного двигателестроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1740000000',0,'ЦСР_2016',1,'Подпрограмма "Авиационные агрегаты и приборы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1740100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка российских организаций в сфере создания и производства современного авиационного бортового электронного оборудования и агрегатов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1740167720',0,'ЦСР_2016',1,'Субсидии российским предприятиям отрасли авиационного агрегатостроения на компенсацию части затрат на реализацию проектов по выходу на мировой рынок в качестве поставщиков компонентов и агрегатов 2 - 4 уровней',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1740167740',0,'ЦСР_2016',1,'Субсидии российским компаниям отрасли авиационного приборостроения на компенсацию части затрат на реализацию проектов выхода предприятий отрасли на мировой рынок в качестве поставщиков компонентов 2 - 4 уровней',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1740200000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение научно-исследовательских и опытно-конструкторских работ в области авиационных агрегатов и приборов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1770000000',0,'ЦСР_2016',1,'Подпрограмма "Авиационная наука и технологии"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1770100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка российских научных организаций, осуществляющих исследования в области развития авиации и авиационной деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1770200000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение научно-исследовательских работ в целях развития науки и технологий в авиастроении и технологической и инженерной инфраструктуры, в том числе на базе инновационных территориальных кластеров"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1780000000',0,'ЦСР_2016',1,'Подпрограмма "Комплексное развитие отрасли"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1780100000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-аналитическое обеспечение реализации государственной программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1780200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка авиационной промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1780264750',0,'ЦСР_2016',1,'Субсидии российским производителям самолетов, вертолетов и авиационных двигателей на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1800000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие судостроения и техники для освоения шельфовых месторождений на 2013 - 2030 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1810000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие судостроительной науки"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1810100000',0,'ЦСР_2016',1,'Основное мероприятие "Создание научно-технического задела для развития морской и речной техники гражданского назначения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1810200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка организаций судостроительной промышленности в целях технического перевооружения уникальных исследовательских, испытательных комплексов и стендов, развития полигонной базы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1810300000',0,'ЦСР_2016',1,'Основное мероприятие "Организация систем отраслевого и междисциплинарного образования в судостроительной отрасли"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1810400000',0,'ЦСР_2016',1,'Основное мероприятие "Системно-аналитическое и экспертное сопровождение научной деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1820000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие технологического потенциала гражданского судостроения и техники для освоения шельфовых месторождений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1820100000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка новых технологий и создание инновационных проектов для производства гражданской морской и речной техники"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1820200000',0,'ЦСР_2016',1,'Основное мероприятие "Закупка передовых зарубежных технологий и лицензий на строительство объектов и организацию в России производства современного технологического оборудования и другой продукции, разработанной ведущими фирмами мира"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1830000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие производственных мощностей гражданского судостроения и материально-технической базы отрасли"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1830100000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация приоритетных проектов развития производственных мощностей гражданского судостроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1830164130',0,'ЦСР_2016',1,'Взнос Российской Федерации в уставный капитал  открытого акционерного общества "Дальневосточный завод "Звезда", г. Большой Камень, Приморский край, на цели возмещения процентов по кредитам, привлеченным в российских банках для реализации проекта "Соз',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1830200000',0,'ЦСР_2016',1,'Основное мероприятие "Создание и реконструкция производственных мощностей российского судостроения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1840000000',0,'ЦСР_2016',1,'Подпрограмма "Государственная поддержка"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1840100000',0,'ЦСР_2016',1,'Основное мероприятие "Предоставление государственной поддержки российским судостроительным предприятиям"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1840167960',0,'ЦСР_2016',1,'Взнос Российской Федерации в уставный капитал акционерного общества "Объединенная судостроительная корпорация", г. Санкт-Петербург, в целях погашения кредита (основного долга и процентов), привлеченного для покупки на торгах, организованных Центральн',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1840168841',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного  общества "Объединенная судостроительная корпорация", г. Санкт-Петербург, в целях реализации проектов лизинга пассажирских судов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1840200000',0,'ЦСР_2016',1,'Основное мероприятие "Предоставление государственной поддержки российским транспортным компаниям, пароходствам, организациям рыбохозяйственного комплекса в целях приобретения гражданских судов и (или) утилизации отдельных групп судов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1840264720',0,'ЦСР_2016',1,'Субсидии российским транспортным компаниям и пароходствам на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономической деятельности (Вне',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1840264730',0,'ЦСР_2016',1,'Субсидии российским транспортным компаниям и пароходствам, а также организациям рыбохозяйственного комплекса на возмещение части затрат на уплату лизинговых платежей по договорам лизинга, заключенным в 2008 - 2016 годах с российскими лизинговыми комп',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1840265650',0,'ЦСР_2016',1,'Субсидии российским организациям на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономической деятельности (Внешэкономбанк)" в 2016 - 20',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1870000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие гражданской морской техники" на 2009 - 2016 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1900000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие электронной и радиоэлектронной промышленности на 2013 - 2025 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1930000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие производства телекоммуникационного оборудования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1930100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка создания научно-технического задела"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1930200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка создания производственной базы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1940000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие производства вычислительной техники"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1940100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка создания научно-технического задела"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1940200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка создания производственной базы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1950000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие производства специального технологического оборудования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1950100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка создания научно-технического задела"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1950200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка создания производственной базы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1960000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие производства систем интеллектуального управления"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1960100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка создания научно-технического задела"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1960200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка создания производственной базы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1960267780',0,'ЦСР_2016',1,'Субсидии российским предприятиям радиоэлектронной промышленности на компенсацию части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях на цели реализации проектов по созданию инфраструктуры отрасли, в том числе к',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2000000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие фармацевтической и медицинской промышленности" на 2013 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2010000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие производства лекарственных средств"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2010100000',0,'ЦСР_2016',1,'Основное мероприятие "Организация производства и выпуска инновационных лекарственных препаратов на основе биотехнологий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2010200000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка и выпуск инновационных, импортозамещающих лекарственных препаратов для лечения социально-значимых заболеваний"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2010300000',0,'ЦСР_2016',1,'Основное мероприятие "Организация опытно-промышленного производства субстанций и лекарственных средств, необходимых для выпуска дорогостоящих импортозамещающих препаратов "',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2010400000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация иных проектов в области фармацевтической промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2010460730',0,'ЦСР_2016',1,'Субсидии российским организациям на возмещение части затрат на реализацию проектов по разработке схожих по фармакотерапевтическому действию и улучшенных аналогов инновационных лекарственных препаратов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2010468620',0,'ЦСР_2016',1,'Субсидии российским организациям на возмещение части затрат на реализацию проектов по организации и проведению клинических исследований лекарственных препаратов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2010468630',0,'ЦСР_2016',1,'Субсидии российским организациям на компенсацию части затрат, понесенных при реализации проектов по организации производства лекарственных средств и (или) фармацевтических субстанций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2010500000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование государственного регулирования в сфере обращения лекарственных средств"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2020000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие производства медицинских изделий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2020100000',0,'ЦСР_2016',1,'Основное мероприятие "Организация производства новых радиофармпрепаратов и медицинских изделий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2020200000',0,'ЦСР_2016',1,'Основное мероприятие "Производство медицинской техники для каскадной фильтрации плазмы и других методов экстракорпоральной гемокоррекции"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2020300000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация иных проектов в области медицинской промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2020368600',0,'ЦСР_2016',1,'Субсидии российским организациям на возмещение части затрат на реализацию проектов по организации производства медицинских изделий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2020368610',0,'ЦСР_2016',1,'Субсидии российским организациям на компенсацию части затрат на реализацию проектов по организации и проведению клинических испытаний имплантируемых медицинских изделий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2020400000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование государственного регулирования в сфере обращения медицинских изделий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2040000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие фармацевтической и медицинской промышленности Российской Федерации на период до 2020 года и дальнейшую перспективу"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2100000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Космическая деятельность России на 2013 - 2020 годы"',0,'',0,'','', '19000101',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 '2110000000',0,'ЦСР_2016',1,'Подпрограмма "Приоритетные инновационные проекты ракетно-космической промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2110100000',0,'ЦСР_2016',1,'Основное мероприятие "Создание систем слежения и мониторинга подвижных объектов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2110200000',0,'ЦСР_2016',1,'Основное мероприятие "Создание интеллектуальных систем мониторинга и контроля состояния технически сложных объектов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2110300000',0,'ЦСР_2016',1,'Основное мероприятие "Создание транспортно-энергетического модуля на основе ядерной энергодвигательной установки мегаваттного класса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2120000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Космическая деятельность России на 2013 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2120100000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение функций аппарата ответственного исполнителя"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2120130270',0,'ЦСР_2016',1,'Премии Правительства Российской Федерации имени Ю.А. Гагарина в области космической деятельности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2120200000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение функций по обеспечению отбора и подготовки космонавтов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2120300000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержание потенциала космодрома "Байконур"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2120350110',0,'ЦСР_2016',1,'Дотации на содержание объектов инфраструктуры города Байконура, связанных с арендой космодрома Байконур',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2120351570',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на развитие и поддержку инфраструктуры города Байконура',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2120400000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение международных обязательств"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2120500000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение страхования рисков и ответственности при запусках и летных испытаниях космических аппаратов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2120600000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение деятельности по использованию космического пространства в мирных целях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2120700000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации первоочередных мероприятий, связанных с созданием космодрома "Восточный"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2140000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Поддержание, развитие и использование системы ГЛОНАСС на 2012 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2140062630',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Сибирские приборы и системы", г. Омск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2140062870',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Информационные спутниковые системы" имени академика М.Ф. Решетнёва", г. Железногорск, Красноярский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2140062900',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Концерн воздушно-космической обороны "Алмаз-Антей", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2140062920',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Российская корпорация ракетно-космического приборостроения и информационных систем", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2140063170',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Салют", г. Нижний Новгород',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2140063470',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Завод "Навигатор", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2140063510',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Геофизика-Космос", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2140064380',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-исследовательский институт "Полюс" им. М.Ф. Стельмаха", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2140067670',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Испытательный технический центр - НПО ПМ", г. Железногорск, Красноярский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2140067790',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-производственное предприятие "Квант", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2150000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие российских космодромов на 2006 - 2015 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2150100000',0,'ЦСР_2016',1,'Подпрограмма "Создание обеспечивающей инфраструктуры космодрома "Восточный"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2160000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие космодромов на период 2016 - 2025 годов в обеспечение космической деятельности Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2170000000',0,'ЦСР_2016',1,'Федеральная космическая программа России на 2016 - 2025 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2200000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие атомного энергопромышленного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2210000000',0,'ЦСР_2016',1,'Подпрограмма "Расширение мощностей электрогенерации атомных электростанций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2210100000',0,'ЦСР_2016',1,'Основное мероприятие "Завершение строительства энергоблоков высокой степени готовности и строительство новых энергоблоков"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2210165080',0,'ЦСР_2016',1,'Имущественный взнос в Государственную корпорацию по атомной энергии "Росатом" на развитие атомного энергопромышленного комплекса',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2210200000',0,'ЦСР_2016',1,'Основное мероприятие "Строительство атомных станций малой мощности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2210265080',0,'ЦСР_2016',1,'Имущественный взнос в Государственную корпорацию по атомной энергии "Росатом" на развитие атомного энергопромышленного комплекса',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2210300000',0,'ЦСР_2016',1,'Основное мероприятие "Модернизация действующих атомных электростанций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2210400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение безопасной и устойчивой работы действующих энергоблоков атомных электростанций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2220000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение безопасного обращения с радиоактивными отходами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2220100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение производственной программы по глубинным пунктам захоронения жидких радиоактивных отходов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2220200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение функционирования штатных аварийно-спасательных формирований в атомной отрасли"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2220300000',0,'ЦСР_2016',1,'Основное мероприятие "Обращение с радиоактивными отходами, включая радиоактивные отходы, образующиеся в бюджетных организациях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2220365070',0,'ЦСР_2016',1,'Субсидии на возмещение затрат на обращение с радиоактивными отходами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2230000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение инновационного развития гражданского сектора атомной отрасли и расширение сферы использования ядерных технологий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2230100000',0,'ЦСР_2016',1,'Основное мероприятие "Участие в проекте создания Международного термоядерного экспериментального реактора ИТЭР"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2230200000',0,'ЦСР_2016',1,'Основное мероприятие "Участие в проекте создания Центра по исследованию ионов и антипротонов в Европе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2230300000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-исследовательские и опытно-конструкторские работы в области развития атомной отрасли"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2230400000',0,'ЦСР_2016',1,'Основное мероприятие "Создание инновационного технопарка в интересах развития гражданского сектора атомной отрасли"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2230500000',0,'ЦСР_2016',1,'Основное мероприятие "Проект "Создание типового оптимизированного и информатизированного энергоблока технологии ВВЭР (ВВЭР-ТОИ)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2230600000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение обязательств по внесению взносов в международные организации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2230700000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение международных обязательств по поставке низкообогащенного урана, переработанного из высокообогащенного урана"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2240000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение исполнения Государственной корпорацией по атомной энергии "Росатом" государственных заданий и функций в области государственного управления использованием атомной энергии"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2240100000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение Государственной корпорацией по атомной энергии "Росатом" возложенных на нее государственных полномочий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2240165140',0,'ЦСР_2016',1,'Субсидии Государственной корпорации по атомной энергии "Росатом" на выполнение возложенных на нее государственных полномочий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2240200000',0,'ЦСР_2016',1,'Основное мероприятие "Информационно-аналитическое обеспечение, управление и мониторинг реализации государственной программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2240300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение отрасли квалифицированными выпускниками образовательных учреждений высшего образования, обучающихся по специальностям и направлениям подготовки, связанным с атомной отраслью"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2250000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение производственных, технологических и социально-экономических процессов устойчивого развития ядерного оружейного комплекса Российской Федерации и стратегического присутствия России в Арктической зоне"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2250100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение Вооруженных сил Российской Федерации продукцией и услугами атомной отрасли"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2250200000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование экспериментально-испытательной и производственно-технологической баз в атомной отрасли"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2250300000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка федеральных ядерных центров и специалистов, занятых в выполнении государственного оборонного заказа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2250360590',0,'ЦСР_2016',1,'Субсидии организациям ядерно-оружейного комплекса',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2250400000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование, восстановление и хранение материальных ценностей государственного запаса специального сырья и делящихся материалов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2250500000',0,'ЦСР_2016',1,'Основное мероприятие "Специальные мероприятия в области национальной обороны"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2250567460',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Государственный научный центр Российской Федерации - Физико-энергетический институт имени А.И. Лейпунского", г. Обнинск, Калужская область, в целях технического перевооружения производственной базы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2250600000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по промышленной  утилизации вооружения и военной техники ядерного комплекса, не входящие в Федеральную целевую программу "Промышленная утилизация вооружения и военной техники ядерного комплекса на 2011 - 2015 годы и',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2250700000',0,'ЦСР_2016',1,'Основное мероприятие "Содержание объектов федерального государственного унитарного предприятия атомного флота, связанных с использованием атомной энергии"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2250764590',0,'ЦСР_2016',1,'Субсидии федеральному государственному унитарному предприятию "Атомфлот" на возмещение расходов по содержанию объектов, связанных с использованием атомной энергии',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2250800000',0,'ЦСР_2016',1,'Основное мероприятие "Строительство атомных ледоколов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2270000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Ядерные энерготехнологии нового поколения на период 2010 - 2015 годов и на перспективу до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2270063800',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Сибирский химический комбинат", г. Северск, Томская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2270063810',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Государственный научный центр - Научно-исследовательский институт атомных реакторов", г. Димитровград-10, Ульяновская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2270066700',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Высокотехнологический научно-исследовательский институт неорганических материалов имени академика А.А. Бочвара", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2270066710',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Красная Звезда", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2270067270',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "НИИЭФА им. Д.В. Ефремова", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2270067440',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Государственный научный центр Российской Федерации - Физико-энергетический институт имени А.И. Лейпунского", г. Обнинск, Калужская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2270067450',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Государственный научный центр Российской Федерации Троицкий институт инновационных и термоядерных исследований", г. Москва, г. Троицк',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2280000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие ядерного оружейного комплекса Российской Федерации на 2007 - 2015 годы и на период до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2280060040',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Федеральный центр науки и высоких технологий "Специальное научно-производственное объединение "Элерон", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2280063810',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Государственный научный центр - Научно-исследовательский институт атомных реакторов", г. Димитровград-10, Ульяновская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2280066700',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Высокотехнологический научно-исследовательский институт неорганических материалов имени академика А.А. Бочвара", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2280067440',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Государственный научный центр Российской Федерации - Физико-энергетический институт имени А.И. Лейпунского", г. Обнинск, Калужская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2290000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Промышленная утилизация вооружения и военной техники ядерного комплекса на 2011 - 2015 годы и на период до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2290100000',0,'ЦСР_2016',1,'Подпрограмма "Промышленная утилизация ядерных боеприпасов на 2011 - 2015 годы и на период до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2290200000',0,'ЦСР_2016',1,'Подпрограмма "Промышленная утилизация атомных подводных лодок, надводных кораблей с ядерной энергетической установкой, судов атомного технологического обслуживания и реабилитация радиационно-опасных объектов на 2011 - 2015 годы и на период до 2020 го',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '22Б0000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Обеспечение ядерной и радиационной безопасности на 2016 - 2020 годы и на период до 2030 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '22Б0063690',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Центр судоремонта "Звездочка", г. Северодвинск, Архангельская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '22Б0063800',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Сибирский химический комбинат", г. Северск, Томская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '22Б0067230',0,'ЦСР_2016',1,'Взнос в уставный капитал публичного акционерного общества "Приаргунское производственное горно-химическое объединение", г. Краснокаменск, Забайкальский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2300000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Информационное общество (2011 - 2020 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2310000000',0,'ЦСР_2016',1,'Подпрограмма "Информационно-телекоммуникационная инфраструктура информационного общества и услуги, оказываемые на ее основе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2310100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение доступности услуг электросвязи на территории Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2310164530',0,'ЦСР_2016',1,'Субсидии на возмещение операторам связи убытков, причиняемых оказанием универсальных услуг связи, а также на возмещение затрат оператору базы данных перенесенных абонентских номеров',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2310200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие федеральной почтовой связи"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2310300000',0,'ЦСР_2016',1,'Основное мероприятие "Расширение использования радиочастотного спектра в гражданских целях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2310400000',0,'ЦСР_2016',1,'Основное мероприятие "Управление развитием информационно-коммуникационной инфраструктуры информационного общества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2310500000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие связи и информационных технологий в целях осуществления подготовки и проведения в Российской Федерации спортивных мероприятий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320000000',0,'ЦСР_2016',1,'Подпрограмма "Информационная среда"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320100000',0,'ЦСР_2016',1,'Основное мероприятие "Строительство, восстановление, реконструкция, переоборудование объектов телерадиовещания"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320160080',0,'ЦСР_2016',1,'Субсидии федеральному государственному унитарному предприятию "Российская телевизионная и радиовещательная сеть" на финансовое обеспечение (возмещение) затрат, связанных с обеспечением устойчивости функционирования сети телерадиовещания в Российской',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320164960',0,'ЦСР_2016',1,'Субсидии федеральному государственному унитарному предприятию "Телевизионный технический центр "Останкино" на проведение капитального ремонта инженерного оборудования и техническое перевооружение производственно-технологического оборудования',0,'',0,'','', '19000101',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 '2320200000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка печатных средств массовой информации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320300000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка создания и распространения телерадиопрограмм и электронных средств массовых информаций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320362420',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "Общественное телевидение России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320364950',0,'ЦСР_2016',1,'Субсидии федеральному государственному унитарному предприятию "Всероссийская государственная телевизионная и радиовещательная компания" на финансовое обеспечение деятельности, а также на покрытие расходов, связанных с производством программного проду',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320364970',0,'ЦСР_2016',1,'Субсидии открытому акционерному обществу "Первый канал", акционерному обществу "Телекомпания НТВ", открытому акционерному обществу "Телерадиокомпания "Петербург", закрытому акционерному обществу "Карусель", акционерному обществу "ТВ Центр" и обществу',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320367170',0,'ЦСР_2016',1,'Субсидии федеральному государственному унитарному предприятию "Всероссийская государственная телевизионная и радиовещательная компания" на финансовое обеспечение мероприятий по переходу в 2013 - 2018 годах на производство программ в цифровом формате',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320400000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка социально значимых проектов в медиасреде"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320464940',0,'ЦСР_2016',1,'Субсидии организациям, осуществляющим производство, распространение и тиражирование социально значимых программ в области электронных средств массовой информации, на создание и поддержание в сети "Интернет" сайтов, имеющих социальное или образователь',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320465000',0,'ЦСР_2016',1,'Субсидии издательствам и издающим организациям на реализацию социально значимых проектов, государственную поддержку непериодических изданий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320500000',0,'ЦСР_2016',1,'Основное мероприятие "Участие России в международном информационном обмене"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320562410',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "ТВ-Новости" на создание средств массовой информации: телеканалов, радиоканалов, сетевых изданий и их распространение в мировом информационном пространстве, покрытие расходов, связанных с производством и',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320564170',0,'ЦСР_2016',1,'Субсидии федеральному государственному унитарному предприятию "Международное информационное агентство "Россия сегодня"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320564930',0,'ЦСР_2016',1,'Субсидии федеральному государственному унитарному предприятию "Информационное телеграфное агентство России (ИТАР - ТАСС)" на финансовое обеспечение расходов по организации мероприятий по освещению государственной политики и общественной жизни в Росси',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320600000',0,'ЦСР_2016',1,'Основное мероприятие "Стимулирование профессиональной деятельности в области средств массовой информации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320700000',0,'ЦСР_2016',1,'Основное мероприятие "Ведение федеральных информационных фондов, баз и банков данных"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320764540',0,'ЦСР_2016',1,'Субсидии организациям, осуществляющим ведение федеральных информационных фондов, баз и банков данных',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2320800000',0,'ЦСР_2016',1,'Основное мероприятие "Управление развитием информационной среды"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2330000000',0,'ЦСР_2016',1,'Подпрограмма "Безопасность в информационном обществе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2330100000',0,'ЦСР_2016',1,'Основное мероприятие "Контроль и надзор в сфере связи, информационных технологий и массовых коммуникаций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2330200000',0,'ЦСР_2016',1,'Основное мероприятие "Организация деятельности радиочастотной службы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2330264560',0,'ЦСР_2016',1,'Субсидия федеральным государственным унитарным предприятиям - радиочастотным центрам федеральных округов на финансовое обеспечение затрат, связанных с выполнением возложенных на них функций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2330265660',0,'ЦСР_2016',1,'Субсидия федеральному государственному унитарному предприятию "Главный радиочастотный центр" на возмещение затрат, связанных с выполнением работ по образованию позывных сигналов для опознавания радиоэлектронных средств гражданского назначения и прове',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2330300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие сети станций радиоконтроля"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2330400000',0,'ЦСР_2016',1,'Основное мероприятие "Предупреждение информационно-технологических угроз национальным интересам России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2330460030',0,'ЦСР_2016',1,'Коллективная разработка отечественного инфраструктурного программного обеспечения на базе свободного программного обеспечения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2330500000',0,'ЦСР_2016',1,'Основное мероприятие "Информационно-техническое сопровождение, модернизация, развитие программно-технических средств подсистемы мониторинга средств массовой информации в специальных целях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2330600000',0,'ЦСР_2016',1,'Основное мероприятие "Противодействие терроризму, экстремизму, насилию"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2340000000',0,'ЦСР_2016',1,'Подпрограмма "Информационное государство"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2340100000',0,'ЦСР_2016',1,'Основное мероприятие "Управление развитием информационного общества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2340200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие и эксплуатация электронного правительства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2340300000',0,'ЦСР_2016',1,'Основное мероприятие "Создание и внедрение современных информационных технологий в сфере государственного управления"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2340400000',0,'ЦСР_2016',1,'Основное мероприятие "Создание и развитие официальных сайтов высших должностных лиц и органов управления Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2340500000',0,'ЦСР_2016',1,'Основное мероприятие "Координация мероприятий по использованию информационно-коммуникационных технологий в деятельности государственных органов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2340600000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка региональных проектов в сфере информационных технологий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2340650280',0,'ЦСР_2016',1,'Субсидии на поддержку региональных проектов в сфере информационных технологий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2340700000',0,'ЦСР_2016',1,'Основное мероприятие "Информатизация в сфере оказания государственных услуг и контроля качества их предоставления, осуществления государственных функций и информационной открытости органов власти"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2340800000',0,'ЦСР_2016',1,'Основное мероприятие "Информационно-технологическое и информационно-аналитическое обеспечение деятельности отдельных органов государственной власти"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2340900000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие сервисов на основе информационных технологий в области медицины, здравоохранения, социального обеспечения, образования, науки и культуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2341000000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие и эксплуатация государственной системы изготовления, оформления и контроля паспортно-визовых документов нового поколения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2350000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие телерадиовещания в Российской Федерации на 2009 - 2018 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2400000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие транспортной системы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2410000000',0,'ЦСР_2016',1,'Подпрограмма "Магистральный железнодорожный транспорт"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2410100000',0,'ЦСР_2016',1,'Основное мероприятие "Компенсация потерь в доходах транспортных предприятий, возникающих в результате государственного регулирования тарифов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2410154750',0,'ЦСР_2016',1,'Иные межбюджетные трансферты бюджету Калининградской области на компенсацию части затрат российских юридических лиц на перевозку железнодорожным транспортом общего пользования готовых товаров, произведенных на территории Калининградской области, на т',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2410160790',0,'ЦСР_2016',1,'Субсидии организациям железнодорожного транспорта на компенсацию потерь в доходах, возникающих в результате государственного регулирования тарифов на перевозку пассажиров в поездах дальнего следования в плацкартных и общих вагонах',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2410160800',0,'ЦСР_2016',1,'Субсидии организациям железнодорожного транспорта на компенсацию потерь в доходах, возникающих в результате установления льгот по тарифам на перевозку обучающихся и воспитанников общеобразовательных учреждений старше 10 лет железнодорожным транспорто',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2410160810',0,'ЦСР_2016',1,'Субсидии открытому акционерному обществу "Российские железные дороги" на компенсацию потерь в доходах, возникающих в результате государственного регулирования тарифов на услуги по использованию инфраструктуры железнодорожного транспорта общего пользо',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2410164470',0,'ЦСР_2016',1,'Субсидии организациям железнодорожного транспорта на компенсацию потерь в доходах от выравнивания тарифов при перевозке пассажиров в сообщении из (в) Калининградской области в (из) другие регионы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2410200000',0,'ЦСР_2016',1,'Основное мероприятие "Модернизация транспортной инфраструктуры железнодорожного транспорта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2410251540',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на реализацию мероприятий по подготовке и проведению чемпионата мира по футболу в 2018 году в Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2410264000',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Российские железные дороги"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2410300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2420000000',0,'ЦСР_2016',1,'Подпрограмма "Дорожное хозяйство"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2420100000',0,'ЦСР_2016',1,'Основное мероприятие "Капитальный ремонт, ремонт и содержание автомобильных дорог общего пользования федерального значения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2420200000',0,'ЦСР_2016',1,'Основное мероприятие "Обновление парка автоколонн войскового типа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2420264500',0,'ЦСР_2016',1,'Субсидии организациям транспорта, осуществляющим приобретение автотехники для пополнения подвижного состава автоколонн войскового типа',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2420300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2420320910',0,'ЦСР_2016',1,'Плата концедента в рамках заключенных концессионных соглашений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2420400000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие развитию автомобильных дорог регионального, межмуниципального и местного значения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2420453900',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на финансовое обеспечение дорожной деятельности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2420454200',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на реализацию мероприятий региональных программ в сфере дорожного хозяйства, включая проекты, реализуемые с применением механизмов государственно-частного партнерства, и строительство, реконструкцию и ремонт уникальных ис',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2420500000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие скоростных автомобильных дорог на условиях государственно-частного партнерства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2420565130',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в Государственную компанию "Российские автомобильные дороги"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2420565150',0,'ЦСР_2016',1,'Субсидии Государственной компании "Российские автомобильные дороги" на осуществление деятельности по доверительному управлению автомобильными дорогами Государственной компании',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430000000',0,'ЦСР_2016',1,'Подпрограмма "Гражданская авиация и аэронавигационное обслуживание"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430100000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие повышению доступности воздушных перевозок населения, в том числе в части развития региональных и внутрирегиональных перевозок"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430160780',0,'ЦСР_2016',1,'Субсидии организациям воздушного транспорта в целях обеспечения доступности внутренних региональных перевозок пассажиров воздушным транспортом в Приволжском федеральном округе',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430164160',0,'ЦСР_2016',1,'Субсидии организациям воздушного транспорта на осуществление региональных воздушных перевозок пассажиров на территории Российской Федерации и формирование региональной маршрутной сети',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430164340',0,'ЦСР_2016',1,'Субсидии на возмещение российским авиакомпаниям части затрат на уплату лизинговых платежей за воздушные суда отечественного производства, получаемые российскими авиакомпаниями от российских лизинговых компаний по договорам лизинга в 2002 - 2010 годах',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430164350',0,'ЦСР_2016',1,'Субсидии на возмещение российским авиакомпаниям, региональным унитарным предприятиям, не являющимся российскими авиакомпаниями, части затрат на уплату лизинговых или арендных платежей за воздушные суда, получаемые указанными организациями по договора',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430164360',0,'ЦСР_2016',1,'Субсидии на обеспечение доступности воздушных перевозок пассажиров с Дальнего Востока в европейскую часть страны и в обратном направлении',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430164400',0,'ЦСР_2016',1,'Субсидии на обеспечение доступности воздушных перевозок пассажиров из г. Калининграда в европейскую часть страны и в обратном направлении',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430164550',0,'ЦСР_2016',1,'Субсидии организациям воздушного транспорта в целях обеспечения доступности воздушных перевозок пассажиров в г. Симферополь и в обратном направлении',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430167080',0,'ЦСР_2016',1,'Субсидии авиационным перевозчикам для возмещения недополученных ими доходов в связи с обеспечением перевозки пассажиров, заключивших договор воздушной перевозки с авиационным перевозчиком, в отношении которого принято решение о приостановлении действ',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка авиапредприятий, расположенных в районах Крайнего Севера и приравненных к ним местностях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430264320',0,'ЦСР_2016',1,'Субсидии аэропортам, расположенным в районах Крайнего Севера и приравненных к ним местностях',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430264390',0,'ЦСР_2016',1,'Субсидии федеральным казенным предприятиям, расположенным в районах Крайнего Севера и приравненных к ним местностях',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение охвата территории Российской Федерации деятельностью специализированных поисково- и аварийно-спасательных служб на воздушном транспорте"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430364310',0,'ЦСР_2016',1,'Субсидии авиационным предприятиям и организациям экспериментальной авиации на возмещение затрат при осуществлении ими поисково-спасательных операций (работ) и участии в их обеспечении',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430400000',0,'ЦСР_2016',1,'Основное мероприятие "Возмещение расходов за аэронавигационное обслуживание и услуги по аэропортовому и наземному обеспечению полетов воздушных судов пользователей воздушного пространства, освобожденных в соответствии с законодательством Российской Ф',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430464300',0,'ЦСР_2016',1,'Субсидии на возмещение расходов за аэронавигационное обслуживание полетов воздушных судов пользователей воздушного пространства, освобожденных в соответствии с законодательством Российской Федерации от платы за аэронавигационное обслуживание',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430464370',0,'ЦСР_2016',1,'Субсидии на возмещение организациям недополученных доходов от предоставления услуг по аэропортовому и наземному обеспечению полетов воздушных судов пользователей воздушного пространства, освобожденных в соответствии с законодательством Российской Фед',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430500000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2430564330',0,'ЦСР_2016',1,'Субсидии на функционирование координационного центра Россия - НАТО',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2440000000',0,'ЦСР_2016',1,'Подпрограмма "Морской и речной транспорт"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2440100000',0,'ЦСР_2016',1,'Основное мероприятие "Поисковое и аварийно-спасательное обеспечение судоходства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2440164420',0,'ЦСР_2016',1,'Субсидии на выполнение мероприятий по несению аварийно-спасательной готовности на море',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2440200000',0,'ЦСР_2016',1,'Основное мероприятие "Навигационно-гидрографическое обеспечение судоходства на трассах Северного морского пути"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2440264450',0,'ЦСР_2016',1,'Субсидии на навигационно-гидрографическое обеспечение судоходства на трассах Северного морского пути',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2440300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение эксплуатации внутренних водных путей и гидротехнических сооружений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2440400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2450000000',0,'ЦСР_2016',1,'Подпрограмма "Надзор в сфере транспорта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2450100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение функционирования и развития системы государственного контроля и надзора в сфере транспорта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2450200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие и обеспечение функционирования единой информационно-аналитической системы (ЕИАС)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2480000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение реализации программы, включая развитие транспортной инфраструктуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2480100000',0,'ЦСР_2016',1,'Основное мероприятие "Управление реализацией Программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2480120480',0,'ЦСР_2016',1,'Создание федеральной государственной информационной системы навигации на автомобильных дорогах',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2480160610',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "Единая транспортная дирекция" на организацию перевозок пассажиров в прямом смешанном сообщении на территорию Крымского федерального округа и в обратном направлении',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2480162210',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "Дирекция Московского транспортного узла"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2480162230',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "Дирекция по развитию транспортной системы Санкт-Петербурга и Ленинградской области"',0,'',0,'','', '19000101',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 '2480162240',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "Единая транспортная дирекция"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2480162310',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "Транспортная дирекция чемпионата мира по футболу 2018 года в Российской Федерации", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2480200000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие развитию транспортной инфраструктуры города Москвы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2480254050',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на развитие транспортной инфраструктуры города Москвы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2480300000',0,'ЦСР_2016',1,'Основное мероприятие "Комплексная программа обеспечения безопасности населения на транспорте"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б0000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие транспортной системы России (2010 - 2020 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б0100000',0,'ЦСР_2016',1,'Подпрограмма "Развитие экспорта транспортных услуг"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б0200000',0,'ЦСР_2016',1,'Подпрограмма "Железнодорожный транспорт"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б0264180',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Российские железные дороги" в рамках реализации мероприятий подпрограммы "Железнодорожный транспорт" федеральной целевой программы "Развитие транспортной системы России (2010 - 2020 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б0300000',0,'ЦСР_2016',1,'Подпрограмма "Автомобильные дороги"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б0351150',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий подпрограммы "Автомобильные дороги" федеральной целевой программы "Развитие транспортной системы России (2010 - 2020 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б0351950',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий по подготовке и проведению чемпионата мира по футболу в 2018 году в Российской Федерации по подпрограмме "Автомобильные дороги" федеральной целевой программы "Развитие транспортной системы России (2010 - 2020 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б0400000',0,'ЦСР_2016',1,'Подпрограмма "Морской транспорт"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б0500000',0,'ЦСР_2016',1,'Подпрограмма "Внутренний водный транспорт"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б0600000',0,'ЦСР_2016',1,'Подпрограмма "Гражданская авиация"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б0651160',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий подпрограммы "Гражданская авиация" федеральной целевой программы "Развитие транспортной системы России (2010 - 2020 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б0700000',0,'ЦСР_2016',1,'Подпрограмма "Государственный контроль и надзор в сфере транспорта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Б9900000',0,'ЦСР_2016',1,'Реализация мероприятий общепрограммного характера по федеральной целевой программе',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Г0000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Модернизация Единой системы организации воздушного движения Российской Федерации (2009 - 2020 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Д0000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие гражданского использования системы ГЛОНАСС на транспорте"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Д0100000',0,'ЦСР_2016',1,'Основное мероприятие "Создание и обеспечение постоянной эксплуатации системы экстренного реагирования при авариях "ЭРА-ГЛОНАСС"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Д0160050',0,'ЦСР_2016',1,'Субсидия акционерному обществу "ГЛОНАСС" в целях финансового обеспечения (возмещения) затрат в связи с функционированием Государственной автоматизированной информационной системы "ЭРА-ГЛОНАСС"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Д0200000',0,'ЦСР_2016',1,'Основное мероприятие "Создание региональных информационно-навигационных систем в субъектах Российской Федерации, функционирующих с использованием технологий ГЛОНАСС"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Е0000000',0,'ЦСР_2016',1,'Подпрограмма "Перевод автомобильного, железнодорожного, авиационного, морского и речного транспорта на использование газомоторного топлива"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Е0100000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка и реализация мер по поэтапному переходу на использование газомоторного топлива в транспортном комплексе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '24Е0200000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-техническое обеспечение реализации Подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2500000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Государственная программа развития сельского хозяйства и регулирования рынков сельскохозяйственной продукции, сырья и продовольствия на 2013 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие подотрасли растениеводства, переработки и реализации продукции растениеводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие садоводства, поддержка закладки и ухода за многолетними насаждениями и виноградниками"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510150320',0,'ЦСР_2016',1,'Субсидии на возмещение части затрат на закладку и уход за виноградниками',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510150330',0,'ЦСР_2016',1,'Субсидии на возмещение части затрат на раскорчевку выбывших из эксплуатации старых садов и рекультивацию раскорчеванных площадей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510150340',0,'ЦСР_2016',1,'Субсидии на возмещение части затрат на закладку и уход за многолетними плодовыми и ягодными насаждениями',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510154370',0,'ЦСР_2016',1,'Субсидии на возмещение части прямых понесенных затрат на создание и модернизацию объектов плодохранилищ, а также на приобретение техники и оборудования на цели предоставления субсидий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510200000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка экономически значимых программ субъектов Российской Федерации в области растениеводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510250350',0,'ЦСР_2016',1,'Субсидии на поддержку экономически значимых региональных программ в области растениеводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510300000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка сельскохозяйственных товаропроизводителей в районах Крайнего Севера и приравненных к ним местностях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510350360',0,'ЦСР_2016',1,'Субсидии на возмещение части затрат на приобретение семян с учетом доставки в районы Крайнего Севера и приравненные к ним местности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510350370',0,'ЦСР_2016',1,'Субсидии на производство продукции растениеводства на низкопродуктивной пашне в районах Крайнего Севера и приравненных к ним местностях',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510400000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка кредитования подотрасли растениеводства, переработки ее продукции, развития инфраструктуры и логистического обеспечения рынков продукции растениеводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510450380',0,'ЦСР_2016',1,'Субсидии на возмещение части процентной ставки по краткосрочным кредитам (займам) на развитие растениеводства, переработки и реализации продукции растениеводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510450390',0,'ЦСР_2016',1,'Субсидии на возмещение части процентной ставки по инвестиционным кредитам (займам) на развитие растениеводства, переработки и развитие инфраструктуры и логистического обеспечения рынков продукции растениеводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510500000',0,'ЦСР_2016',1,'Основное мероприятие "Управление рисками в подотраслях растениеводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510550400',0,'ЦСР_2016',1,'Субсидии на возмещение части затрат сельскохозяйственных товаропроизводителей на уплату страховой премии, начисленной по договору сельскохозяйственного страхования в области растениеводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510600000',0,'ЦСР_2016',1,'Основное мероприятие "Регулирование рынков продукции растениеводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510700000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание несвязанной поддержки сельскохозяйственным товаропроизводителям в области растениеводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2510750410',0,'ЦСР_2016',1,'Субсидии на оказание несвязанной поддержки сельскохозяйственным товаропроизводителям в области растениеводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие подотрасли животноводства, переработки и реализации продукции животноводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие овцеводства и козоводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520150440',0,'ЦСР_2016',1,'Субсидии на возмещение части затрат по наращиванию маточного поголовья овец и коз',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие северного оленеводства и табунного коневодства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520250450',0,'ЦСР_2016',1,'Субсидии на возмещение части затрат по наращиванию поголовья северных оленей, маралов и мясных табунных лошадей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520300000',0,'ЦСР_2016',1,'Основное мероприятие "Предупреждение распространения и ликвидация африканской чумы свиней на территории Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение проведения противоэпизоотических мероприятий в субъектах Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520467430',0,'ЦСР_2016',1,'Субсидии федеральным казенным предприятиям, отнесенным к ведению Минсельхоза России, на финансовое обеспечение затрат, связанных с производством и доставкой в субъекты Российской Федерации лекарственных средств и препаратов для ветеринарного применен',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520500000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка экономически значимых региональных программ развития сельского хозяйства субъектов Российской Федерации в области животноводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520550460',0,'ЦСР_2016',1,'Субсидии на поддержку экономически значимых региональных программ в области животноводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520600000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка кредитования подотрасли животноводства, переработки ее продукции, развития инфраструктуры и логистического обеспечения рынков продукции животноводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520650470',0,'ЦСР_2016',1,'Субсидии на возмещение части процентной ставки по краткосрочным кредитам (займам) на развитие животноводства, переработки и реализации продукции животноводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520650480',0,'ЦСР_2016',1,'Субсидии на возмещение части процентной ставки по инвестиционным кредитам (займам) на развитие животноводства, переработки и развитие инфраструктуры и логистического обеспечения рынков продукции животноводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520700000',0,'ЦСР_2016',1,'Основное мероприятие "Управление рисками в подотраслях животноводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520750490',0,'ЦСР_2016',1,'Субсидии на возмещение части затрат сельскохозяйственных товаропроизводителей на уплату страховой премии, начисленной по договору сельскохозяйственного страхования в области животноводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520800000',0,'ЦСР_2016',1,'Основное мероприятие "Регулирование рынков продукции животноводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520900000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие производства тонкорунной и полутонкорунной шерсти"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2520954360',0,'ЦСР_2016',1,'Субсидии на поддержку производства и реализации тонкорунной и полутонкорунной шерсти',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2530000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие мясного скотоводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2530100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка товарного маточного поголовья крупного рогатого скота мясных пород и их помесей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2530154530',0,'ЦСР_2016',1,'Субсидии на содержание товарного маточного поголовья крупного рогатого скота мясных пород и их помесей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2530200000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка экономически значимых программ субъектов Российской Федерации в области мясного скотоводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2530250510',0,'ЦСР_2016',1,'Субсидии на поддержку экономически значимых региональных программ по развитию мясного скотоводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2530300000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка строительства и реконструкции объектов для мясного скотоводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2530350520',0,'ЦСР_2016',1,'Субсидии на возмещение части процентной ставки по инвестиционным кредитам на строительство и реконструкцию объектов мясного скотоводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2540000000',0,'ЦСР_2016',1,'Подпрограмма "Поддержка малых форм хозяйствования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2540100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка кредитования малых форм хозяйствования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2540150550',0,'ЦСР_2016',1,'Субсидии на возмещение части процентной ставки по долгосрочным, среднесрочным и краткосрочным кредитам, взятым малыми формами хозяйствования',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2540200000',0,'ЦСР_2016',1,'Основное мероприятие "Оформление земельных участков в собственность крестьянскими (фермерскими) хозяйствами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2540300000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка начинающих фермеров"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2540350530',0,'ЦСР_2016',1,'Субсидии на поддержку начинающих фермеров',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2540400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие семейных животноводческих ферм на базе крестьянских (фермерских) хозяйств"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2540450540',0,'ЦСР_2016',1,'Субсидии на развитие семейных животноводческих ферм',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2540500000',0,'ЦСР_2016',1,'Ведомственная целевая программа "О развитии сельскохозяйственной кооперации на 2014 - 2017 годы и на период до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2540554380',0,'ЦСР_2016',1,'Субсидии на грантовую поддержку сельскохозяйственных потребительских кооперативов для развития материально-технической базы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2550000000',0,'ЦСР_2016',1,'Подпрограмма "Техническая и технологическая модернизация, инновационное развитие"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2550100000',0,'ЦСР_2016',1,'Основное мероприятие "Обновление парка сельскохозяйственной техники"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2550164250',0,'ЦСР_2016',1,'Субсидии производителям сельскохозяйственной техники',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2550200000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация перспективных инновационных проектов в агропромышленном комплексе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2550267360',0,'ЦСР_2016',1,'Гранты в форме субсидий на реализацию перспективных инновационных проектов в агропромышленном комплексе',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2550300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие биотехнологии"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2550400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие рынка лизинга сельскохозяйственной техники и оборудования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2560000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Государственная программа развития сельского хозяйства и регулирования рынков сельскохозяйственной продукции, сырья и продовольствия на          2013 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2560100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование управления реализацией Программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2560200000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы налогообложения в сельском хозяйстве"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2560300000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование механизма финансового оздоровления сельскохозяйственных товаропроизводителей в рамках Федерального закона "О финансовом оздоровлении сельскохозяйственных товаропроизводителей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2560400000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание государственных услуг и выполнение работ в рамках реализации государственной программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2560500000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование государственных информационных ресурсов в сферах обеспечения продовольственной безопасности и управления агропромышленным комплексом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2560600000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение государственного мониторинга земель сельскохозяйственного назначения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2560700000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение функций в области ветеринарного и фитосанитарного надзора"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2560754840',0,'ЦСР_2016',1,'Субвенции бюджетам Республики Крым и города федерального значения Севастополя на осуществление части переданных полномочий Российской Федерации в области ветеринарного и фитосанитарного надзора',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2560800000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление компенсации понесенных затрат сельскохозяйственных товаропроизводителей вследствие причиненного ущерба в результате чрезвычайных ситуаций природного характера"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2570000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Устойчивое развитие сельских территорий на 2014 - 2017 годы и на период до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2570050180',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий федеральной целевой программы "Устойчивое развитие сельских территорий на 2014 - 2017 годы и на период до 2020 года"',0,'',0,'','', '19000101',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 '2580000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие мелиорации земель сельскохозяйственного назначения России на 2014 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2580050760',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий федеральной целевой программы "Развитие мелиорации земель сельскохозяйственного назначения России на 2014 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2590000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие овощеводства открытого и защищенного грунта и семенного картофелеводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2590100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие производства семенного картофеля и овощей открытого грунта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2590154390',0,'ЦСР_2016',1,'Субсидии на оказание несвязанной поддержки сельскохозяйственным товаропроизводителям в области развития производства семенного картофеля и овощей открытого грунта',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2590154400',0,'ЦСР_2016',1,'Субсидии на возмещение части прямых понесенных затрат на создание и модернизацию объектов картофелехранилищ и овощехранилищ, а также на приобретение техники и оборудования на цели предоставления субсидии',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2590200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие производства овощей защищенного грунта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2590254410',0,'ЦСР_2016',1,'Субсидии на возмещение части прямых понесенных затрат на создание и модернизацию объектов тепличных комплексов, а также на приобретение техники и оборудования на цели предоставления субсидии',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Б0000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие молочного скотоводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Б0100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие молочного скотоводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Б0150430',0,'ЦСР_2016',1,'Субсидии на 1 килограмм реализованного и (или) отгруженного на собственную переработку молока',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Б0154420',0,'ЦСР_2016',1,'Субсидии на возмещение части прямых понесенных затрат на создание и модернизацию объектов животноводческих комплексов молочного направления (молочных ферм), а также на приобретение техники и оборудования на цели предоставления субсидии',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Б0200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка кредитования подотрасли молочного скотоводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Б0254430',0,'ЦСР_2016',1,'Субсидии на возмещение части процентной ставки по краткосрочным кредитам (займам) на развитие молочного скотоводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Б0254440',0,'ЦСР_2016',1,'Субсидии на возмещение части процентной ставки по инвестиционным кредитам (займам) на строительство и реконструкцию объектов для молочного скотоводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Б0300000',0,'ЦСР_2016',1,'Основное мероприятие "Идентификация маточного поголовья крупного рогатого скота молочного направления"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0000000',0,'ЦСР_2016',1,'Подпрограмма "Поддержка племенного дела, селекции и семеноводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие элитного семеноводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0150310',0,'ЦСР_2016',1,'Субсидии на возмещение части затрат на приобретение элитных семян',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0160310',0,'ЦСР_2016',1,'Гранты государственным учреждениям на сохранение коллекции генетических ресурсов растений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0200000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка племенного животноводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0250420',0,'ЦСР_2016',1,'Субсидии на поддержку племенного животноводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие племенной базы молочного скотоводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0354460',0,'ЦСР_2016',1,'Субсидии на поддержку племенного крупного рогатого скота молочного направления',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие племенной базы мясного скотоводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0450500',0,'ЦСР_2016',1,'Субсидии на поддержку племенного крупного рогатого скота мясного направления',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0500000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка строительства объектов селекционно-генетических и селекционно-семеноводческих центров"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0554470',0,'ЦСР_2016',1,'Субсидии на возмещение части прямых понесенных затрат на создание и модернизацию объектов селекционно-генетических центров в животноводстве и селекционно-семеноводческих центров в растениеводстве, а также на приобретение техники и оборудования на цел',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0600000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка кредитования развития селекционно-генетических и селекционно-семеноводческих центров в подотраслях животноводства и растениеводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Г0654480',0,'ЦСР_2016',1,'Субсидии на возмещение части процентной ставки по краткосрочным кредитам (займам) на развитие селекционно-генетических и селекционно-семеноводческих центров в подотраслях животноводства и растениеводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Д0000000',0,'ЦСР_2016',1,'Подпрограмма  "Развитие оптово-распределительных центров и инфраструктуры системы социального питания"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Д0100000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка кредитования развития оптово-распределительных центров, производства и товаропроводящей инфраструктуры системы социального питания"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Д0154500',0,'ЦСР_2016',1,'Субсидии на возмещение части процентной ставки по краткосрочным кредитам (займам) на переработку продукции растениеводства и животноводства в области развития оптово-распределительных центров',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Д0154510',0,'ЦСР_2016',1,'Субсидии на возмещение части процентной ставки по инвестиционным кредитам (займам) на развитие оптово-распределительных центров, производства и товаропроводящей инфраструктуры системы социального питания',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Д0200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка строительства объектов оптово-распределительных центров, производства и товаропроводящей инфраструктуры системы социального питания"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Д0254520',0,'ЦСР_2016',1,'Субсидии на возмещение части прямых понесенных затрат на создание оптово-распределительных центров, а также на приобретение техники и оборудования на цели предоставления субсидии',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Ж0000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие финансово-кредитной системы агропромышленного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Ж0100000',0,'ЦСР_2016',1,'Основное мероприятие "Докапитализация акционерного общества "Россельхозбанк"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Ж0167330',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Россельхозбанк", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '25Ж0200000',0,'ЦСР_2016',1,'Основное мероприятие "Докапитализация открытого акционерного общества "Росагролизинг"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2600000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие рыбохозяйственного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2610000000',0,'ЦСР_2016',1,'Подпрограмма "Организация рыболовства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2610100000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение эффективности в области организации рыболовства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2610200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие промышленного и прибрежного рыболовства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2610300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие рыболовства в районах действия международных договоров Российской Федерации в области рыболовства и сохранения водных биологических ресурсов и открытой части Мирового океана"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2610400000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование работы государственного рыбохозяйственного реестра и повышение эффективности его использования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2620000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие аквакультуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2620100000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление работ по искусственному воспроизводству водных биологических ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2620200000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление работ по сохранению водных биологических ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2620300000',0,'ЦСР_2016',1,'Основное мероприятие "Информационное обеспечение деятельности предприятий аквакультуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2620400000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка субъектов аквакультуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2620453960',0,'ЦСР_2016',1,'Субсидии сельскохозяйственным товаропроизводителям на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях, на развитие аквакультуры (рыбоводство)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2620500000',0,'ЦСР_2016',1,'Основное мероприятие "Стимулирование научно-исследовательской и опытно-конструкторской деятельности в области аквакультуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2630000000',0,'ЦСР_2016',1,'Подпрограмма "Наука и инновации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2630100000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение рыбохозяйственных исследований"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2630200000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение научно-исследовательских работ в области формирования инфраструктуры и развития рыбохозяйственного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2640000000',0,'ЦСР_2016',1,'Подпрограмма "Охрана и контроль"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2640100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование деятельности по предупреждению, сдерживанию и ликвидации незаконного, несообщаемого и нерегулируемого промысла водных биологических ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2640200000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение безопасности плавания судов рыбопромыслового флота и выполнение комплекса аварийно-спасательных работ на рыбопромысловых судах в районах промысла при осуществлении рыболовства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2640300000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование разграничения полномочий в области контроля, надзора и охраны водных биологических ресурсов на внутренних водных объектах рыбохозяйственного значения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2640400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение государственного контроля (надзора) в области рыболовства и сохранения водных биологических ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2640500000',0,'ЦСР_2016',1,'Основное мероприятие "Информационное обеспечение деятельности рыбохозяйственного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2650000000',0,'ЦСР_2016',1,'Подпрограмма "Модернизация и стимулирование"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2650100000',0,'ЦСР_2016',1,'Основное мероприятие "Стимулирование модернизации существующего и строительства нового рыбопромыслового флота"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2650164270',0,'ЦСР_2016',1,'Субсидии на возмещение рыбохозяйственным организациям и индивидуальным предпринимателям части затрат на уплату процентов по инвестиционным кредитам, полученным в российских кредитных организациях, на строительство и модернизацию рыбопромысловых судов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2650200000',0,'ЦСР_2016',1,'Основное мероприятие "Стимулирование модернизации и строительства объектов рыбоперерабатывающей инфраструктуры, объектов хранения рыбной продукции"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2650264280',0,'ЦСР_2016',1,'Субсидии на возмещение рыбохозяйственным организациям и индивидуальным предпринимателям части затрат на уплату процентов по инвестиционным кредитам, полученным в российских кредитных организациях, на строительство и модернизацию объектов рыбоперераба',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2650300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие выставочной деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2660000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Развитие рыбохозяйственного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2660100000',0,'ЦСР_2016',1,'Основное мероприятие "Руководство и управление в сфере установленных функций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2660200000',0,'ЦСР_2016',1,'Основное мероприятие "Мониторинг выполнения государственных услуг и работ в рамках реализации государственной программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2670000000',0,'ЦСР_2016',1,'Подпрограмма "Повышение эффективности использования и развитие ресурсного потенциала рыбохозяйственного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2670100000',0,'ЦСР_2016',1,'Основное мероприятие "Строительство и реконструкция рыбоводных заводов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2670200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие научно-производственной базы аквакультуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2670300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение эффективной и безопасной добычи водных биологических ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2670400000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение качества государственного мониторинга контроля добычи водных биологических ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2670500000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция объектов федеральной собственности портовых сооружений рыбных терминалов морских портов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2670600000',0,'ЦСР_2016',1,'Основное мероприятие "Комплексная капитальная реконструкция научно-исследовательских судов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2680000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие осетрового хозяйства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2680100000',0,'ЦСР_2016',1,'Основное мероприятие "Межведомственное взаимодействие и контроль, направленные на борьбу с незаконной добычей (выловом) осетровых видов рыб"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2680200000',0,'ЦСР_2016',1,'Основное мероприятие "Международная деятельность в области регулирования рыболовства, сохранения и воспроизводства осетровых видов рыб в бассейне Каспийского моря"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2680300000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка товарного осетроводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2680354160',0,'ЦСР_2016',1,'Субсидии на возмещение сельскохозяйственным товаропроизводителям части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях, на развитие товарного осетроводства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2680400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие технологий товарного осетроводства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2680500000',0,'ЦСР_2016',1,'Основное мероприятие "Мониторинг состояния запасов осетровых видов рыб"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2680600000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление работ по искусственному воспроизводству осетровых видов рыб"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2680700000',0,'ЦСР_2016',1,'Основное мероприятие "Мелиорация водных объектов рыбохозяйственного значения (для осетровых видов рыб)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2700000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие внешнеэкономической деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2710000000',0,'ЦСР_2016',1,'Подпрограмма "Реализация приоритетных направлений внешнеэкономической деятельности в процессе международного экономического сотрудничества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2710100000',0,'ЦСР_2016',1,'Основное мероприятие "Расширение двустороннего торгово-экономического сотрудничества с зарубежными странами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2710127970',0,'ЦСР_2016',1,'Субсидии российским организациям на обеспечение деятельности на архипелаге Шпицберген',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2710200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие многостороннего экономического сотрудничества и интеграционных процессов на пространстве Содружества Независимых Государств"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2710300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение участия и защиты интересов Российской Федерации в деятельности Всемирной торговой организации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2710400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие интеграции Российской Федерации в международную экономическую систему, обеспечение участия в международных экономических организациях, форумах и соглашениях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2710500000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие взаимодействия с региональными экономическими организациями"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2720000000',0,'ЦСР_2016',1,'Подпрограмма "Формирование Евразийского экономического союза"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2720100000',0,'ЦСР_2016',1,'Основное мероприятие "Создание, развитие и имплементация системы соглашений по формированию и обеспечению функционирования Евразийского экономического союза"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2720200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение деятельности наднациональных и межгосударственных органов Евразийского экономического союза с передачей им необходимых полномочий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2730000000',0,'ЦСР_2016',1,'Подпрограмма "Создание национальной системы поддержки развития внешнеэкономической деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2730100000',0,'ЦСР_2016',1,'Основное мероприятие "Финансовая поддержка экспорта"',0,'',0,'','', '19000101',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 '2730160130',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в государственную корпорацию "Банк развития и внешнеэкономической деятельности (Внешэкономбанк)" на цели приобретения акций акционерного общества "Российский экспортный центр" в целях увеличения уставного капи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2730200000',0,'ЦСР_2016',1,'Основное мероприятие "Промоутерская поддержка экспорта и инвестиционного сотрудничества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2730300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение планирования, координации и мониторинга внешнеэкономической деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2730400000',0,'ЦСР_2016',1,'Основное мероприятие "Устранение барьеров для экспорта и инвестиций на внешних рынках"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2730500000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие деятельности торговых представительств Российской Федерации в иностранных государствах по продвижению экономических интересов в глобальной экономике"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2730600000',0,'ЦСР_2016',1,'Основное мероприятие "Создание организаций инфраструктуры поддержки субъектов малого и среднего предпринимательства, осуществляющих внешнеэкономическую деятельность"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2730700000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие системы подготовки, переподготовки и повышения квалификации кадров в сфере внешнеэкономической деятельности "',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2740000000',0,'ЦСР_2016',1,'Подпрограмма "Совершенствование системы государственного регулирования внешнеэкономической деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2740100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение эффективной реализации функций внешнеторгового регулирования в формате Таможенного союза"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2740200000',0,'ЦСР_2016',1,'Основное мероприятие "Упрощение административных и налоговых правил и процедур для участников внешнеэкономической деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2750000000',0,'ЦСР_2016',1,'Подпрограмма "Совершенствование таможенной деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2750100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование деятельности таможенных органов Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2750200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие административной и социальной инфраструктуры таможенных органов Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2750300000',0,'ЦСР_2016',1,'Основное мероприятие "Жилищное обеспечение сотрудников таможенных органов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2750400000',0,'ЦСР_2016',1,'Основное мероприятие "Медицинское и санаторно-курортное обеспечение"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2760000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение развития системы пунктов пропуска через Государственную границу Российской Федерации для осуществления внешнеэкономической деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2760100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы пунктов пропуска, создание благоприятных условий для перемещения через государственную границу грузов и пересечения ее физическими лицами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2760200000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление международной деятельности Росграницы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2760300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение деятельности центрального аппарата и территориальных органов Росграницы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2800000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Воспроизводство и использование природных ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2810000000',0,'ЦСР_2016',1,'Подпрограмма "Воспроизводство минерально-сырьевой базы, геологическое изучение недр"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2810100000',0,'ЦСР_2016',1,'Основное мероприятие "Региональные геолого-геофизические и геолого-съемочные работы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2810200000',0,'ЦСР_2016',1,'Основное мероприятие "Работы специального геологического назначения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2810300000',0,'ЦСР_2016',1,'Основное мероприятие "Государственный мониторинг состояния недр, гидрогеологическая и инженерно-геологическая съемка"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2810400000',0,'ЦСР_2016',1,'Основное мероприятие "Государственное геологическое информационное обеспечение"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2810500000',0,'ЦСР_2016',1,'Основное мероприятие "Воспроизводство минерально-сырьевой базы углеводородного сырья"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2810600000',0,'ЦСР_2016',1,'Основное мероприятие "Воспроизводство минерально-сырьевой базы твердых полезных ископаемых"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2810700000',0,'ЦСР_2016',1,'Основное мероприятие "Воспроизводство минерально-сырьевой базы подземных вод (питьевых и минеральных)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2810800000',0,'ЦСР_2016',1,'Основное мероприятие "Воспроизводство минерально-сырьевой базы общераспространенных полезных ископаемых"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2810900000',0,'ЦСР_2016',1,'Основное мероприятие "Воспроизводство минерально-сырьевой базы и геологическое изучение недр в Крымском федеральном округе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2810953950',0,'ЦСР_2016',1,'Субвенции бюджетам Республики Крым и города федерального значения Севастополя на осуществление части полномочий Российской Федерации в сфере недропользования',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2811000000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-аналитическое и инновационное обеспечение государственной политики в сфере развития и использования минерально-сырьевой базы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2811100000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-техническое обеспечение геолого-разведочных работ"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2811200000',0,'ЦСР_2016',1,'Основное мероприятие "Тематические и опытно-методические работы, связанные с геологическим изучением недр и воспроизводством минерально-сырьевой базы, мониторингом недропользования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2811300000',0,'ЦСР_2016',1,'Основное мероприятие "Организация добычи метана угольных пластов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2811400000',0,'ЦСР_2016',1,'Основное мероприятие "Координация и контроль деятельности по реализации государственной системы лицензирования пользования недрами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2811500000',0,'ЦСР_2016',1,'Основное мероприятие "Модернизация, проектирование и строительство научно-исследовательских судов и технологического оборудования для работ в Мировом океане, а также в пределах континентального шельфа, Арктики и Антарктики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2811600000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение эффективной реализации государственных функций в сфере недропользования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2811653950',0,'ЦСР_2016',1,'Субвенции бюджетам Республики Крым и города федерального значения Севастополя на осуществление части полномочий Российской Федерации в сфере недропользования',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2811700000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение участия Российской Федерации в международных организациях (соглашениях) в сфере геологического изучения недр и воспроизводства минерально-сырьевой базы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2820000000',0,'ЦСР_2016',1,'Подпрограмма "Использование водных ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2820100000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативно-правовое и научно-методическое обеспечение реализации государственной политики в сфере использования водных ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2820200000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление нормирования водопользования, мониторинга водных объектов и других водохозяйственных мероприятий текущего характера"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2820300000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение работ по содержанию и обеспечению безопасной эксплуатации гидротехнических сооружений и охрана водохранилищ"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2820400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение исполнения субъектами Российской Федерации переданных полномочий Российской Федерации в области водных отношений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2820451280',0,'ЦСР_2016',1,'Субвенции на осуществление отдельных полномочий в области водных отношений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2820500000',0,'ЦСР_2016',1,'Основное мероприятие "Создание и эксплуатация защитных сооружений от наводнений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2820564290',0,'ЦСР_2016',1,'Субсидии на содержание комплекса защитных сооружений г. Санкт-Петербурга от наводнений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2820600000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение эффективной реализации государственных функций в сфере водных отношений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2820654140',0,'ЦСР_2016',1,'Субвенции бюджетам Республики Крым и города федерального значения Севастополя на осуществление части полномочий Российской Федерации в области водных отношений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2830000000',0,'ЦСР_2016',1,'Подпрограмма "Сохранение и воспроизводство охотничьих ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2830100000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-аналитическое и инновационное обеспечение сохранения и воспроизводства охотничьих ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2830200000',0,'ЦСР_2016',1,'Основное мероприятие "Информационно-аналитическое обеспечение в сфере сохранения и воспроизводства охотничьих ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2830300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение сохранения и воспроизводства охотничьих ресурсов в государственных опытных охотничьих хозяйствах"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2830400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение эффективного исполнения субъектами Российской Федерации переданных полномочий Российской Федерации в области охоты и сохранения охотничьих ресурсов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2860000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие водохозяйственного комплекса Российской Федерации в 2012 - 2020 годах"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2860050160',0,'ЦСР_2016',1,'Субсидии на мероприятия федеральной целевой программы "Развитие водохозяйственного комплекса Российской Федерации в 2012 - 2020 годах"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2900000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие лесного хозяйства" на 2013 - 2020 годы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2910000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение использования, охраны, защиты и воспроизводства лесов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2910100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение контроля пожарной опасности в лесах и готовности к действиям сил и средств, предназначенных для предупреждения и ликвидации чрезвычайных ситуаций в лесах, возникших вследствие лесных пожаров"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2910200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственный лесопатологический мониторинг в лесах, расположенных на землях лесного фонда"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2910300000',0,'ЦСР_2016',1,'Основное мероприятие "Радиационный мониторинг лесов, расположенных на землях лесного фонда"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2910400000',0,'ЦСР_2016',1,'Основное мероприятие "Государственный мониторинг воспроизводства лесов, формирование и хранение федерального фонда семян лесных растений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2910500000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение исполнения переданных субъектам Российской Федерации полномочий Российской Федерации в области лесных отношений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2910551290',0,'ЦСР_2016',1,'Субвенции на осуществление отдельных полномочий в области лесных отношений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2910551310',0,'ЦСР_2016',1,'Субсидии на приобретение специализированной лесопожарной техники и оборудования',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2910552210',0,'ЦСР_2016',1,'Субвенции бюджетам Республики Крым и города федерального значения Севастополя на осуществление части полномочий Российской Федерации в области лесных отношений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2910553980',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на софинансирование расходов Республики Алтай по договору финансовой аренды (лизинга) вертолета',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2940000000',0,'ЦСР_2016',1,'Подпрограмма "Стратегическое управление лесным хозяйством"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2940100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение стратегического управления лесным хозяйством"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2940200000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-аналитическое обеспечение в сфере реализации государственной программы, направленное на повышение научно-технического потенциала лесного сектора экономики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2940300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение исполнения государственных функций Рослесхозом, формирование условий для участия граждан в принятии решений в области лесных отношений, развитие международного сотрудничества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3000000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Энергоэффективность и развитие энергетики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3010000000',0,'ЦСР_2016',1,'Подпрограмма "Энергосбережение и повышение энергетической эффективности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3010100000',0,'ЦСР_2016',1,'Основное мероприятие "Создание благоприятных условий для формирования институтов и инфраструктуры, способствующих энергосбережению и повышению энергетической эффективности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3010200000',0,'ЦСР_2016',1,'Основное мероприятие "Создание благоприятных условий и снижение административных и иных барьеров в целях привлечения инвестиций в область энергосбережения и повышения энергетической эффективности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3010300000',0,'ЦСР_2016',1,'Основное мероприятие "Информационное обеспечение и пропаганда энергосбережения и повышения энергетической эффективности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3010400000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка мероприятий (проектов) в области энергосбережения и повышения энергетической эффективности в субъектах Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3010500000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение научно-исследовательских работ в области энергосбережения и повышения энергетической эффективности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3010600000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация образовательных программ в области энергосбережения и повышения энергетической эффективности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3020000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие и модернизация электроэнергетики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3020100000',0,'ЦСР_2016',1,'Основное мероприятие "Модернизация и новое строительство генерирующих мощностей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3020200000',0,'ЦСР_2016',1,'Основное мероприятие "Модернизация и новое строительство электросетевых объектов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3020267940',0,'ЦСР_2016',1,'Взнос в уставный капитал публичного акционерного общества "Российские сети", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3020300000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение доступности энергетической инфраструктуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3020400000',0,'ЦСР_2016',1,'Основное мероприятие "Ликвидация межтерриториального перекрестного субсидирования в электроэнергетике"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3020500000',0,'ЦСР_2016',1,'Основное мероприятие "Возмещение недополученных доходов сетевых организаций в результате отмены или продления механизма "последней мили"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3030000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие нефтяной отрасли"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3030100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение уровней добычи нефти на месторождениях, находящихся в стадии эксплуатации, и развитие новых центров нефтедобычи"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3030200000',0,'ЦСР_2016',1,'Основное мероприятие "Строительство, модернизация, реконструкция и эксплуатация трубопроводных систем"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3030300000',0,'ЦСР_2016',1,'Основное мероприятие "Строительство, модернизация, реконструкция нефтеперерабатывающих предприятий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3040000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие газовой отрасли"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3040100000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение технологического перевооружения газовой отрасли за счет внедрения энергосберегающих и энергоэффективных технологий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3040200000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация проектов по реконструкции существующих и строительству новых мощностей транспортировки газа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3040300000',0,'ЦСР_2016',1,'Основное мероприятие "Расширение действующих и строительство новых подземных хранилищ газа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3040400000',0,'ЦСР_2016',1,'Основное мероприятие "Создание системы сбыта сжиженного природного газа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3040500000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка и внедрение новых отечественных технологий производства сжиженного природного газа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3040600000',0,'ЦСР_2016',1,'Основное мероприятие "Строительство, модернизация, реконструкция нефтегазохимических предприятий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3050000000',0,'ЦСР_2016',1,'Подпрограмма "Реструктуризация и развитие угольной и торфяной промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3050100000',0,'ЦСР_2016',1,'Основное мероприятие "Модернизация действующих предприятий на основе инновационных технологий "',0,'',0,'','', '19000101',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 '3050200000',0,'ЦСР_2016',1,'Основное мероприятие "Создание новых центров угледобычи на месторождениях с благоприятными горно-геологическими условиями"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3050300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение промышленной и экологической безопасности и охраны труда"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3050400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие добычи торфа "',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3050500000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие внутреннего рынка угольной продукции"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3050600000',0,'ЦСР_2016',1,'Основное мероприятие "Укрепление позиций России на мировом рынке угля"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3050700000',0,'ЦСР_2016',1,'Основное мероприятие "Реструктуризация угольной промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3050751560',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на реализацию программ местного развития и обеспечение занятости для шахтерских городов и поселков',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3060000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие использования возобновляемых источников энергии"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3060100000',0,'ЦСР_2016',1,'Основное мероприятие "Стимулирование производства электрической энергии генерирующими объектами, функционирующими на основе использования возобновляемых источников энергии"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3060200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка технологического присоединения  генерирующих объектов, функционирующих на основе использования возобновляемых источников энергии"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3060300000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение оценки технического и экономического потенциала использования возобновляемых источников энергии в Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3060400000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка генерации на основе использования возобновляемых источников энергии"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3070000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Энергоэффективность и развитие энергетики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3070100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование процессов сбора, обработки, хранения и использования информационных ресурсов топливно-энергетического комплекса и развитие государственной информационной системы топливно-энергетического комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3070200000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование, хранение, ведение и организация использования информационных ресурсов топливно-энергетического комплекса, организационно-технологическое сопровождение функционирования государственной информационной системы топливн',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3070300000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация функций аппарата ответственного исполнителя государственной программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3070400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие международного сотрудничества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3070500000',0,'ЦСР_2016',1,'Основное мероприятие "Инновационное развитие организаций топливно-энергетического комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3200000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Обеспечение государственной безопасности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3210000000',0,'ЦСР_2016',1,'Подпрограмма "Государственная безопасность"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3210100000',0,'ЦСР_2016',1,'Основное мероприятие "Контрразведывательная деятельность"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3210200000',0,'ЦСР_2016',1,'Основное мероприятие "Борьба с терроризмом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3210300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение экономической безопасности, борьба с преступностью и коррупцией"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3210400000',0,'ЦСР_2016',1,'Основное мероприятие "Разведывательная деятельность"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3210500000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение информационной безопасности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3210600000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы "Государственная безопасность"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3220000000',0,'ЦСР_2016',1,'Подпрограмма "Защита и охрана Государственной границы Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3220100000',0,'ЦСР_2016',1,'Основное мероприятие "Охрана Государственной границы, защита экономических и иных законных интересов на суше, реках и озерах Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3220200000',0,'ЦСР_2016',1,'Основное мероприятие "Охрана Государственной границы, защита экономических и иных законных интересов Российской Федерации на морских направлениях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3220300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы "Защита и охрана Государственной границы Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3230000000',0,'ЦСР_2016',1,'Подпрограмма "Противодействие легализации (отмыванию) доходов, полученных преступным путем, и финансированию терроризма"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3230100000',0,'ЦСР_2016',1,'Основное мероприятие "Укрепление и расширение международного сотрудничества в сфере противодействия легализации (отмыванию) доходов, полученных преступным путем, и финансированию терроризма"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3230164140',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "Международный учебно-методический центр финансового мониторинга"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3230200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие информационно-технологического обеспечения в сфере противодействия легализации (отмыванию) доходов, полученных преступным путем, и финансированию терроризма"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3240000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Обеспечение государственной безопасности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3240100000',0,'ЦСР_2016',1,'Основное мероприятие "Содержание аппаратов управления"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3240200000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение прикладных научных исследований в области национальной безопасности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3240300000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление жилищного строительства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3240400000',0,'ЦСР_2016',1,'Основное мероприятие "Содержание образовательных учреждений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3240500000',0,'ЦСР_2016',1,'Основное мероприятие "Содержание учреждений издательств, учреждений культуры, спортивных объектов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3240600000',0,'ЦСР_2016',1,'Основное мероприятие "Содержание учреждений здравоохранения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3240700000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление ежемесячных денежных выплат отдельным категориям граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3240730040',0,'ЦСР_2016',1,'Компенсация в возмещение вреда гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации всл',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3240730050',0,'ЦСР_2016',1,'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 10 января 2002 года № 2-ФЗ "О социальных гарантиях гражданам, подвергшимся радиационному',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3240730140',0,'ЦСР_2016',1,'Возмещение федеральными органами исполнительной власти расходов на погребение',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3240730170',0,'ЦСР_2016',1,'Пособия, выплаты и компенсации членам семей военнослужащих, а также лицам, уволенным с военной службы без права на пенсию',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3260000000',0,'ЦСР_2016',1,'Подпрограмма "Осуществление мероприятий в области обустройства государственной границы Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3270000000',0,'ЦСР_2016',1,'Подпрограмма "Осуществление мероприятий в области технической защиты информации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3400000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Социально-экономическое развитие Дальнего Востока и Байкальского региона"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3410000000',0,'ЦСР_2016',1,'Подпрограмма "Создание условий для опережающего социально-экономического развития Дальневосточного федерального округа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3410100000',0,'ЦСР_2016',1,'Основное мероприятие  "Создание и развитие территорий опережающего социально-экономического развития в Дальневосточном федеральном округе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3410160090',0,'ЦСР_2016',1,'Субсидии управляющей компании, осуществляющей функции по управлению территориями опережающего социально-экономического развития в субъектах Российской Федерации, входящих в состав Дальневосточного федерального округа',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3410160100',0,'ЦСР_2016',1,'Субсидии управляющей компании, осуществляющей функции по управлению территориями опережающего социально-экономического развития в субъектах Российской Федерации, входящих в состав Дальневосточного федерального округа, на финансовое обеспечение затрат',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3410200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие свободного порта Владивосток"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3420000000',0,'ЦСР_2016',1,'Подпрограмма "Поддержка реализации инвестиционных проектов в Дальневосточном федеральном округе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3420100000',0,'ЦСР_2016',1,'Основное мероприятие  "Мероприятия по отбору инвестиционных проектов, планируемых к реализации на территории Дальнего Востока"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3420200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка инвестиционных проектов, реализуемых на территории Дальнего Востока"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3420260110',0,'ЦСР_2016',1,'Субсидии юридическим лицам (за исключением государственных (муниципальных) учреждений) на финансовое обеспечение затрат на создание и (или) реконструкцию объектов инфраструктуры, а также на технологическое присоединение энергопринимающих устройств к',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3430000000',0,'ЦСР_2016',1,'Подпрограмма "Поддержка реализации инвестиционных проектов, планируемых к реализации в Байкальском регионе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3430100000',0,'ЦСР_2016',1,'Основное мероприятие  "Мероприятия по отбору инвестиционных проектов, планируемых к реализации на территории Байкальского региона"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3430200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка инвестиционных проектов, реализуемых на территории Байкальского региона"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3440000000',0,'ЦСР_2016',1,'Подпрограмма "Повышение инвестиционной привлекательности Дальнего Востока"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3440100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение проведения крупных презентационных и дискуссионных мероприятий на территории Дальнего Востока"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3440200000',0,'ЦСР_2016',1,'Основное мероприятие "Содействие привлечению инвестиций и развитию человеческого капитала на территории Дальнего Востока"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3440261800',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в автономную некоммерческую организацию "Агентство по развитию человеческого капитала на Дальнем Востоке"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3440261810',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в автономную некоммерческую организацию "Агентство Дальнего Востока по привлечению инвестиций и поддержке экспорта"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '34Д0000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Социально-экономическое развитие Дальнего Востока и Байкальского региона" и прочие мероприятия в области сбалансированного территориального развития"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '34Д0100000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-методическое, информационное и организационное обеспечение реализации государственной программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '34Д0200000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация мероприятий в области сбалансированного территориального развития Дальневосточного федерального округа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '34Д0300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение деятельности аппарата ответственного исполнителя"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '34Ж0000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Экономическое и социальное развитие Дальнего Востока и Байкальского региона на период до 2018 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '34Ж0052140',0,'ЦСР_2016',1,'Финансовое обеспечение мероприятий по экономическому и социальному развитию Дальнего Востока и Байкальского региона на период до 2018 года',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '34Ж0060290',0,'ЦСР_2016',1,'Взнос в уставный капитал публичного акционерного общества "Федеральная гидрогенерирующая компания - РусГидро",                     г. Красноярск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '34Ж0067240',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Дальневосточная энергетическая управляющая компания", г. Владивосток, Приморский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '34К0000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Социально-экономическое развитие Курильских островов (Сахалинская область) на 2016 - 2025 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '34К0055030',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий федеральной целевой программы "Социально-экономическое развитие Курильских островов (Сахалинская область) на 2016 - 2025 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3500000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие Северо-Кавказского федерального округа" на период до 2025 года',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3510000000',0,'ЦСР_2016',1,'Подпрограмма "Социально-экономическое развитие Ставропольского края на 2016 - 2025 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3510100000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция и строительство объектов (учреждений) общего, дошкольного и профессионального образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3510200000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция и строительство объектов (учреждений) здравоохранения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3510300000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по развитию систем жизнеобеспечения населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3510400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие региона-агломерации Кавказские Минеральные Воды"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3510500000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация проектов развития экономики и социальной сферы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3520000000',0,'ЦСР_2016',1,'Подпрограмма "Социально-экономическое развитие Республики Северная Осетия-Алания на 2016 - 2025 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3520100000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция и строительство объектов (учреждений) общего, дошкольного и профессионального образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3520200000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция и строительство объектов (учреждений) здравоохранения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3520300000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по развитию систем жизнеобеспечения населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3520400000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация проектов развития экономики и социальной сферы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3520500000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие туристско-рекреационных преимуществ"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3530000000',0,'ЦСР_2016',1,'Подпрограмма "Социально-экономическое развитие Республики Ингушетия на 2016 - 2025 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3530100000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция и строительство объектов (учреждений) общего, дошкольного и профессионального образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3530200000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция и строительство объектов (учреждений) здравоохранения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3530300000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по развитию систем жизнеобеспечения населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3530400000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация проектов развития экономики и социальной сферы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3530500000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по строительству коммунальной и инженерной инфраструктуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3530600000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по обеспечению жильем вынужденных переселенцев"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3530700000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по развитию машиностроения и металлообработки"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3530800000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по развитию легкой промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3530900000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по развитию системы энергоснабжения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3540000000',0,'ЦСР_2016',1,'Подпрограмма "Социально-экономическое развитие Карачаево-Черкесской Республики на 2016 - 2025 годы"',0,'',0,'','', '19000101',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 '3540100000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция и строительство объектов (учреждений) общего, дошкольного и профессионального образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3540200000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция и строительство объектов (учреждений) здравоохранения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3540300000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по развитию систем жизнеобеспечения населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3540400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие туристско-рекреационных преимуществ"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3540500000',0,'ЦСР_2016',1,'Основное мероприятие  "Реализация проектов развития экономики и социальной сферы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3550000000',0,'ЦСР_2016',1,'Подпрограмма "Социально-экономическое развитие Кабардино-Балкарской Республики на 2016 - 2025 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3550100000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция и строительство объектов (учреждений) общего, дошкольного и профессионального образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3550200000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция и строительство объектов (учреждений) здравоохранения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3550300000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по развитию систем жизнеобеспечения населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3550400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие туристско-рекреационных преимуществ"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3550500000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация проектов развития экономики и социальной сферы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3560000000',0,'ЦСР_2016',1,'Подпрограмма "Социально-экономическое развитие Республики Дагестан на 2016 - 2025 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3560100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие промышленности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3560200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие электроэнергетики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3560300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие транспортно-логистического комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3560400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие агропромышленного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3560500000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по развитию систем жизнеобеспечения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3560600000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по газификации муниципальных образований"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3560700000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятие по реконструкции и строительству объектов (учреждений) общего, дошкольного и профессионального образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3560800000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по реконструкции и строительству объектов (учреждений) здравоохранения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3560900000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по переселению лакского населения Новолакского района на новое место жительства и восстановлению Ауховского района"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3561000000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по переселению жителей сел Храх-Уба и Урьян-Уба из Азербайджанской Республики на территорию Республики Дагестан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3570000000',0,'ЦСР_2016',1,'Подпрограмма "Социально-экономическое развитие Чеченской Республики на 2016 - 2025 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3570100000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция и строительство объектов (учреждений) общего, дошкольного и профессионального образования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3570200000',0,'ЦСР_2016',1,'Основное мероприятие "Реконструкция и строительство объектов (учреждений) здравоохранения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3570300000',0,'ЦСР_2016',1,'Основное мероприятие "Мероприятия по развитию систем жизнеобеспечения населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3570400000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация проектов развития экономики и социальной сферы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3580000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие туристического кластера в Северо-Кавказском федеральном округе, Краснодарском крае и Республике Адыгея"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3580100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие особых экономических зон туристско-рекреационного кластера в Северо-Кавказском федеральном округе, Краснодарском крае и Республике Адыгея"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3580163980',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Особые экономические зоны" для участия в проекте создания туристического кластера в Северо-Кавказском федеральном округе, Краснодарском крае и Республике Адыгея',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3580200000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка резидентов особых экономических зон в Северо-Кавказском федеральном округе, Краснодарском крае и Республике Адыгея"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3580260010',0,'ЦСР_2016',1,'Субсидии резидентам туристско-рекреационных особых экономических зон, объединенных решением Правительства Российской Федерации в кластер, на возмещение части затрат на уплату процентов по кредитам, привлеченным на финансовое обеспечение строительства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35Г0000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Развитие Северо-Кавказского федерального округа" на период до 2025 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35Г0100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение деятельности Минкавказа России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35Г0200000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка нормативных правовых актов Правительства Российской Федерации, определяющих направления развития Северо-Кавказского федерального округа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35Д0000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Социально-экономическое развитие Республики Ингушетия на 2010 - 2016 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35Д0050190',0,'ЦСР_2016',1,'Субсидии на мероприятия федеральной целевой программы "Социально-экономическое развитие Республики Ингушетия на 2010 - 2016 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35Ж0000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Юг России (2014 - 2020 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35Ж0051010',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий федеральной целевой программы "Юг России (2014 - 2020 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35И0000000',0,'ЦСР_2016',1,'Подпрограмма "Формирование инфраструктуры государственной информационной политики в Северо-Кавказском федеральном округе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35И0100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие комплексного информационного ресурса, посвященного Северо-Кавказскому федеральному округу"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35И0200000',0,'ЦСР_2016',1,'Основное мероприятие "Организационно-аналитическое сопровождение реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35К0000000',0,'ЦСР_2016',1,'Подпрограмма "Создание медицинского кластера на территории Кавказских Минеральных Вод и реализация инвестиционных проектов Северо-Кавказского федерального округа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35К0100000',0,'ЦСР_2016',1,'Основное мероприятие "Создание инновационного медицинского кластера и развитие инвестиционной среды в Северо-Кавказском федеральном округе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35К0167480',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в государственную корпорацию "Банк развития и внешнеэкономической деятельности (Внешэкономбанк)" на увеличение уставного капитала акционерного общества "Корпорация развития Северного Кавказа" в целях создания',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '35К0200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка инвестиционных проектов, реализуемых в Северо-Кавказском федеральном округе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3600000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Развитие федеративных отношений и создание условий для эффективного и ответственного управления региональными и муниципальными финансами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3610000000',0,'ЦСР_2016',1,'Подпрограмма "Совершенствование системы распределения и перераспределения финансовых ресурсов между уровнями бюджетной системы Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3610100000',0,'ЦСР_2016',1,'Основное мероприятие "Актуализация форм и механизмов предоставления межбюджетных трансфертов бюджетам субъектов Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3610200000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение эффективности предоставления нецелевых межбюджетных трансфертов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3610300000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение эффективности предоставления и использования межбюджетных субсидий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3610400000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение эффективности предоставления и использования субвенций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3610459000',0,'ЦСР_2016',1,'Единая субвенция бюджетам субъектов Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3610500000',0,'ЦСР_2016',1,'Основное мероприятие "Актуализация распределения доходных источников между уровнями бюджетной системы Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620000000',0,'ЦСР_2016',1,'Подпрограмма "Выравнивание финансовых возможностей бюджетов субъектов Российской Федерации и местных бюджетов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620100000',0,'ЦСР_2016',1,'Основное мероприятие "Выравнивание бюджетной обеспеченности субъектов Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620150010',0,'ЦСР_2016',1,'Дотации на выравнивание бюджетной обеспеченности субъектов Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620200000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка мер по обеспечению сбалансированности бюджетов субъектов Российской Федерации и муниципальных образований и компенсация дополнительных расходов, возникших в результате решений, принятых органами власти другого уровня"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620250020',0,'ЦСР_2016',1,'Дотации на поддержку мер по обеспечению сбалансированности бюджетов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620250060',0,'ЦСР_2016',1,'Дотация в целях обеспечения сбалансированности бюджета Чеченской Республики',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620250090',0,'ЦСР_2016',1,'Дотации на частичную компенсацию дополнительных расходов на повышение оплаты труда работников бюджетной сферы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620251250',0,'ЦСР_2016',1,'Дотации бюджету Приморского края в целях обеспечения сбалансированности бюджета городского округа Большой Камень',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620251400',0,'ЦСР_2016',1,'Дотации бюджету Мурманской области в целях обеспечения сбалансированности бюджета городского округа Мурманск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620253840',0,'ЦСР_2016',1,'Дотации на частичную компенсацию расходов бюджетов субъектов Российской Федерации по компенсации отдельным категориям граждан оплаты взноса на капитальный ремонт общего имущества в многоквартирном доме',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620254100',0,'ЦСР_2016',1,'Дотация в целях обеспечения сбалансированности бюджета города федерального значения Севастополя',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620300000',0,'ЦСР_2016',1,'Основное мероприятие "Предоставление дополнительной финансовой помощи в виде бюджетных кредитов бюджетам субъектов Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620400000',0,'ЦСР_2016',1,'Основное мероприятие "Создание условий для устойчивого исполнения бюджетов закрытых административно-территориальных образований"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3620450100',0,'ЦСР_2016',1,'Дотации, связанные с особым режимом безопасного функционирования закрытых административно-территориальных образований',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3630000000',0,'ЦСР_2016',1,'Подпрограмма "Содействие повышению качества управления региональными и муниципальными финансами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3630100000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка реализации региональных программ повышения эффективности бюджетных расходов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3630200000',0,'ЦСР_2016',1,'Основное мероприятие "Оценка качества управления региональными и муниципальными финансами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3630300000',0,'ЦСР_2016',1,'Основное мероприятие "Использование мер ограничительного и стимулирующего характера, направленных на повышение качества управления региональными и муниципальными финансами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3630400000',0,'ЦСР_2016',1,'Основное мероприятие "Методическая поддержка реализации мероприятий по повышению качества управления государственными финансами субъектов Российской Федерации и муниципальными финансами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3640000000',0,'ЦСР_2016',1,'Подпрограмма "Совершенствование системы разграничения расходных полномочий между федеральными органами исполнительной власти, органами государственной власти субъектов Российской Федерации и органами местного самоуправления"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3640100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование правовой и методической базы для осуществления переданных субъектам Российской Федерации полномочий и организации эффективного контроля за осуществлением переданных субъектам Российской Федерации полномочий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3640200000',0,'ЦСР_2016',1,'Основное мероприятие "Участие в рамках положений Конституции Российской Федерации в законодательной деятельности, осуществляемой на уровне Российской Федерации по вопросам совершенствования федеративных отношений и разграничения полномочий между уров',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3640300000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование организации местного самоуправления в Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3700000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Социально-экономическое развитие Калининградской области до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3730000000',0,'ЦСР_2016',1,'Подпрограмма "Создание условий для устойчивого социально-экономического развития Калининградской области"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3730100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие нормативной правовой базы и формирование стратегических документов по вопросам развития Калининградской области"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3730200000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативно-методическое и организационно-аналитическое сопровождение реализации государственной программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3730300000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка организаций, осуществляющих свою деятельность на территории Калининградской области"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3730355040',0,'ЦСР_2016',1,'Иные межбюджетные трансферты бюджету Калининградской области на обеспечение поддержки юридических лиц, осуществляющих деятельность на территории Калининградской области, и резидентов Особой экономической зоны в Калининградской области',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3740000000',0,'ЦСР_2016',1,'Федеральная целевая программа развития Калининградской области на период до 2020 года',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3740050990',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий федеральной целевой программы развития Калининградской области на период до 2020 года',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3800000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Управление федеральным имуществом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3810000000',0,'ЦСР_2016',1,'Подпрограмма "Повышение эффективности управления федеральным имуществом и приватизации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3810100000',0,'ЦСР_2016',1,'Основное мероприятие "Определение целевой функции управления объектами федерального имущества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3810200000',0,'ЦСР_2016',1,'Основное мероприятие "Управление отчуждением объектов федерального имущества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3810300000',0,'ЦСР_2016',1,'Основное мероприятие "Управление развитием объектов федерального имущества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3810400000',0,'ЦСР_2016',1,'Основное мероприятие "Управление рисками в сфере реализации процессов управления федеральным имуществом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3810500000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование учета и мониторинга использования федерального имущества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3810600000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3810654830',0,'ЦСР_2016',1,'Субвенции бюджетам Республики Крым и города федерального значения Севастополя на осуществление части переданных полномочий Российской Федерации в сфере управления федеральным имуществом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3820000000',0,'ЦСР_2016',1,'Подпрограмма "Управление государственным материальным резервом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3820100000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование запасов государственного материального резерва"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3820200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение функционирования управления в сфере государственного материального резерва"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3820300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие инфраструктуры системы государственного материального резерва"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3900000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Управление государственными финансами и регулирование финансовых рынков"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3910000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение сбалансированности федерального бюджета и повышение эффективности бюджетных расходов"',0,'',0,'','', '19000101',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 '3910100000',0,'ЦСР_2016',1,'Основное мероприятие "Внедрение долгосрочного бюджетного планирования в Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3910200000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие программно-целевых методов планирования и повышение эффективности бюджетных расходов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3910300000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие нормативно-правового и методического обеспечения оказания государственных (муниципальных) услуг"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3910400000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование системы материальной мотивации федеральных государственных гражданских  служащих и лиц, замещающих государственные должности Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3910500000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование механизмов финансового обеспечения социальной поддержки населения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3910600000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование регулирования вопросов деятельности государственных внебюджетных фондов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3920000000',0,'ЦСР_2016',1,'Подпрограмма "Нормативно-методическое обеспечение и организация бюджетного процесса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3920100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование бюджетного законодательства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3920200000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативное правовое регулирование и организационно-методическое обеспечение бюджетного процесса на федеральном уровне"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3920300000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование и исполнение федерального бюджета"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3920400000',0,'ЦСР_2016',1,'Основное мероприятие "Кассовое обслуживание исполнения бюджетов бюджетной системы Российской Федерации, учет операций со средствами неучастников бюджетного процесса и формирование бюджетной отчетности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3920500000',0,'ЦСР_2016',1,'Основное мероприятие "Управление резервными средствами федерального бюджета"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3920520540',0,'ЦСР_2016',1,'Резервный фонд Правительства Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3920520550',0,'ЦСР_2016',1,'Резервный фонд Президента Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3920600000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение защиты интересов Российской Федерации в судебных разбирательствах на территории Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3920700000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение качества финансового менеджмента главных администраторов средств федерального бюджета"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3930000000',0,'ЦСР_2016',1,'Подпрограмма "Организация и осуществление контроля и надзора в финансово-бюджетной сфере"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3930100000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативное правовое регулирование и методическое обеспечение по вопросам контроля и надзора в финансово-бюджетной сфере"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3930200000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление внутреннего государственного (муниципального) финансового контроля"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3930300000',0,'ЦСР_2016',1,'Основное мероприятие "Анализ осуществления главными администраторами средств федерального бюджета внутреннего финансового контроля и внутреннего финансового аудита"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3930400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3930500000',0,'ЦСР_2016',1,'Основное мероприятие "Организация и осуществление контрольно-надзорной деятельности в сфере валютных правоотношений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3930600000',0,'ЦСР_2016',1,'Основное мероприятие "Организация и осуществление внешнего контроля качества работы аудиторских организаций, проводящих обязательный аудит бухгалтерской (финансовой) отчетности организаций, определенных действующим законодательством"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3930700000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие информационной инфраструктуры Росфиннадзора и его территориальных органов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3940000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение функционирования и развитие налоговой системы Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3940100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие налогового и таможенного законодательства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3940200000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование налогового администрирования"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3940300000',0,'ЦСР_2016',1,'Основное мероприятие "Разработка основных направлений налоговой политики на очередной финансовый год и плановый период"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3940400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие электронного документооборота между налоговыми органами и налогоплательщиками,  повышение качества исполнения налоговых процедур и информирования налогоплательщиков"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3940500000',0,'ЦСР_2016',1,'Основное мероприятие "Деофшоризация национальной экономики"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3940600000',0,'ЦСР_2016',1,'Основное мероприятие "Взаимодействие с Организацией экономического сотрудничества и развития в рамках реализации плана мероприятий по противодействию размыванию налогооблагаемой базы и выводу прибыли из-под налогообложения (BEPS)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3950000000',0,'ЦСР_2016',1,'Подпрограмма "Управление государственным долгом и государственными финансовыми активами Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3950100000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативное правовое регулирование в сфере управления государственным долгом и государственными финансовыми активами Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3950200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение своевременности и полноты исполнения долговых обязательств Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3950300000',0,'ЦСР_2016',1,'Основное мероприятие "Управление государственным долгом, выраженным в ценных бумагах"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3950400000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание государственной гарантийной поддержки национальной промышленности, реализации инвестиционных проектов (в том числе региональных), экспорта, развития малого и среднего предпринимательства, выполнения гособоронзаказа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3950500000',0,'ЦСР_2016',1,'Основное мероприятие "Взаимодействие с международными рейтинговыми агентствами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3950600000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение эффективного диалога с участниками национального и международного рынков капитала"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3950700000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение обязательств по выплате вознаграждений агентам и консультантам"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3950800000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации межправительственных соглашений об урегулировании (погашении) задолженности Российской Федерации и бывшего СССР перед иностранными государствами-кредиторами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3950900000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение защиты интересов Российской Федерации в международных судебных и иных юридических спорах, касающихся финансовых претензий к Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3951000000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации соглашений Российской Федерации с правительствами иностранных государств-заёмщиками"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3951100000',0,'ЦСР_2016',1,'Основное мероприятие "Управление средствами суверенных фондов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3951200000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативное правовое регулирование и методическое обеспечение по вопросам государственных заимствований субъектов Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3960000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие международного финансово-экономического сотрудничества Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3960100000',0,'ЦСР_2016',1,'Основное мероприятие "Подготовка и аналитическое обеспечение участия Российской Федерации в международных мероприятиях и инициативах в финансово-экономической сфере"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3960200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации политики Российской Федерации в сфере международных финансово-экономических отношений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3960300000',0,'ЦСР_2016',1,'Основное мероприятие "Координация подготовки и реализации проектов, осуществляемых в Российской Федерации при участии международных финансовых организаций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3970000000',0,'ЦСР_2016',1,'Подпрограмма "Создание и развитие государственной интегрированной информационной системы управления общественными финансами "Электронный бюджет"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3970100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование информационного обеспечения бюджетных правоотношений "',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3970200000',0,'ЦСР_2016',1,'Основное мероприятие "Создание централизованных технологий хранения и обработки информации в сфере управления общественными финансами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3970300000',0,'ЦСР_2016',1,'Основное мероприятие "Сопровождение бюджетного процесса, а также исполнения иных функций и полномочий Минфина России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3970400000',0,'ЦСР_2016',1,'Основное мероприятие "Создание и развитие публичных информационных ресурсов в сфере бюджетных правоотношений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3980000000',0,'ЦСР_2016',1,'Подпрограмма "Государственное регулирование отрасли драгоценных металлов и драгоценных камней"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3980100000',0,'ЦСР_2016',1,'Основное мероприятие "Выработка и совершенствование государственной политики и нормативное правовое регулирование в сфере добычи, производства, переработки, использования и обращения драгоценных металлов и драгоценных камней"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3980200000',0,'ЦСР_2016',1,'Основное мероприятие "Организация формирования Государственного фонда драгоценных металлов и драгоценных камней Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3980300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение осуществления федерального пробирного надзора, в том числе опробования и клеймения государственным пробирным клеймом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3990000000',0,'ЦСР_2016',1,'Подпрограмма "Государственное регулирование в сфере производства и оборота этилового спирта, алкогольной и спиртосодержащей продукции"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3990100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3990200000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование нормативной правовой базы в сфере производства и оборота этилового спирта, алкогольной и спиртосодержащей продукции"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3990300000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование государственного контроля и надзора за производством, оборотом, качеством и безопасностью этилового спирта, алкогольной и спиртосодержащей продукции"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39Б0000000',0,'ЦСР_2016',1,'Подпрограмма "Эффективное функционирование финансовых рынков, банковской, страховой деятельности, схем инвестирования и защиты пенсионных накоплений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39Б0100000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие финансовых рынков, создание международного финансового центра"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39Б0200000',0,'ЦСР_2016',1,'Основное мероприятие "Регулирование банковской деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39Б0300000',0,'ЦСР_2016',1,'Основное мероприятие "Регулирование страховой деятельности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39Б0400000',0,'ЦСР_2016',1,'Основное мероприятие "Регулирование обязательных пенсионных накоплений, деятельности негосударственных пенсионных фондов и размещения активов институтов развития"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39Б0500000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование валютного законодательства Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39Б0600000',0,'ЦСР_2016',1,'Основное мероприятие "Защита прав инвесторов и потребителей финансовых услуг"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39Б0700000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие правовой базы бухгалтерского учета и обеспечение применения международных стандартов финансовой отчетности на территории Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39Б0800000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие правовой базы аудиторской деятельности и создание нормативно-методологических основ применения международных стандартов аудита на территории Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39Б0900000',0,'ЦСР_2016',1,'Основное мероприятие "Осуществление государственного контроля (надзора) за деятельностью саморегулируемых организаций аудиторов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39В0000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение открытости и прозрачности управления общественными финансами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39В0100000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение открытости и доступности информации о деятельности публично-правовых образований в сфере управления общественными финансами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39В0200000',0,'ЦСР_2016',1,'Основное мероприятие "Формирование и публикация в открытых источниках "Бюджета для граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '39В0300000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение информационной открытости деятельности исполнителей государственной программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4100000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Внешнеполитическая деятельность"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4110000000',0,'ЦСР_2016',1,'Подпрограмма "Осуществление функций по выработке и реализации государственной политики и нормативно-правовому регулированию в сфере международных отношений Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4110100000',0,'ЦСР_2016',1,'Основное мероприятие "Восстановление, ремонт, благоустройство и уход за российскими (советскими) воинскими захоронениями за рубежом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4110200000',0,'ЦСР_2016',1,'Основное мероприятие "Выполнение международных обязательств по обеспечению деятельности Бюро ЮНЕСКО в г. Москве"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4110300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение участия Российской Федерации в деятельности международных организаций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4110400000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка соотечественников, проживающих за рубежом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4110500000',0,'ЦСР_2016',1,'Основное мероприятие "Участие воинских формирований Вооруженных Сил Российской Федерации в деятельности по поддержанию международного мира и безопасности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4110600000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание гуманитарной помощи иностранным государствам и эвакуация российских граждан"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4110700000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка отдельных некоммерческих организаций в сфере международного сотрудничества"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4110767070',0,'ЦСР_2016',1,'Субсидии на поддержку культурных и духовных центров за рубежом в соответствии с решениями Правительства Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4110800000',0,'ЦСР_2016',1,'Основное мероприятие "Оказание финансовой помощи Республике Южная Осетия"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4110900000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение сотрудничества с Республикой Абхазия в целях ее социально-экономического и научно-технического развития"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4111000000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4111100000',0,'ЦСР_2016',1,'Основное мероприятие "Военно-техническое сотрудничество с иностранными государствами"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4120000000',0,'ЦСР_2016',1,'Подпрограмма "Выполнение финансовых обязательств Российской Федерации по обеспечению деятельности межгосударственных структур, созданных государствами Содружества Независимых Государств"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4120100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение долевого участия Российской Федерации в содержании межгосударственных структур, созданных государствами Содружества Независимых Государств"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4120200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение долевого участия Российской Федерации в финансировании совместных мероприятий, проводимых государствами Содружества Независимых Государств"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4120300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение долевого участия Российской Федерации в формировании бюджета Союзного государства"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4120400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение долевого участия Российской Федерации в Организации Договора о коллективной безопасности"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4130000000',0,'ЦСР_2016',1,'Подпрограмма "Осуществление деятельности в сферах международного гуманитарного сотрудничества и содействия международному развитию"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4130100000',0,'ЦСР_2016',1,'Основное мероприятие "Поддержка российского культурно-гуманитарного присутствия за рубежом"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4130200000',0,'ЦСР_2016',1,'Основное мероприятие "Создание условий для активизации деятельности соотечественников, проживающих за рубежом, в культурно-гуманитарной сфере"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4130300000',0,'ЦСР_2016',1,'Основное мероприятие "Реализация отдельных направлений в области содействия международному развитию"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4130400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4200000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Юстиция"',0,'',0,'','', '19000101',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 '4210000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение защиты публичных интересов, реализации прав граждан и организаций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4210100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование нормативной правовой базы в сфере реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4210200000',0,'ЦСР_2016',1,'Основное мероприятие "Аккредитация обособленных структурных подразделений иностранных юридических лиц"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4210300000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение прав физических и юридических лиц на получение информации о нормативных правовых актах Российской Федерации на основе проведения единой научно-технической политики в области информатизации, развития государственных и',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4210400000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение исполнения решений Европейского суда по правам человека"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4210500000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение реализации переданных субъектам Российской Федерации полномочий Российской Федерации по государственной регистрации актов гражданского состояния"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4220000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие судебно-экспертных учреждений Министерства юстиции Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4220100000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование нормативной правовой базы в сфере реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4220200000',0,'ЦСР_2016',1,'Основное мероприятие "Организация, обеспечение и совершенствование деятельности судебно-экспертных учреждений Минюста России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4220300000',0,'ЦСР_2016',1,'Основное мероприятие "Укрепление международного сотрудничества судебно-экспертных учреждений Минюста России, прохождение аккредитации на соответствие международным стандартам"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4220400000',0,'ЦСР_2016',1,'Основное мероприятие "Завершение мероприятий по совершенствованию статуса государственного судебного эксперта, правового положения и организации государственных судебно-экспертных учреждений Минюста России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4230000000',0,'ЦСР_2016',1,'Подпрограмма "Регулирование государственной политики в сфере исполнения уголовных наказаний"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4230100000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение социальных гарантий лиц, ранее проходивших службу в уголовно-исполнительной системе"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4230200000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение эффективности управления уголовно-исполнительной системой, использование инновационных разработок и научного потенциала"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4230300000',0,'ЦСР_2016',1,'Основное мероприятие "Повышение социального статуса сотрудников уголовно-исполнительной системы, престижа службы в исправительных учреждениях"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4230400000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие международного сотрудничества с пенитенциарными системами иностранных государств, международными органами и неправительственными организациями"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4230500000',0,'ЦСР_2016',1,'Основное мероприятие "Проведение социальной, психологической, воспитательной и образовательной работы с осужденными"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4230600000',0,'ЦСР_2016',1,'Основное мероприятие "Развитие системы наказаний, альтернативных лишению свободы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4230700000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение постпенитенциарной адаптации осужденных, предотвращение рецидива преступлений"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4230800000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение соблюдения международных стандартов обращения с осужденными в местах лишения свободы и лицами, содержащимися под стражей"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4240000000',0,'ЦСР_2016',1,'Подпрограмма "Повышение качества принудительного исполнения судебных актов, актов других органов и должностных лиц и обеспечение установленного порядка деятельности судов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4240100000',0,'ЦСР_2016',1,'Основное мероприятие "Организация и обеспечение принудительного исполнения судебных актов, актов других органов и должностных лиц, а также установленного порядка деятельности судов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4240200000',0,'ЦСР_2016',1,'Основное мероприятие "Модернизация системы принудительного исполнения судебных актов, актов других органов и должностных лиц"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4240300000',0,'ЦСР_2016',1,'Основное мероприятие "Совершенствование нормативной правовой базы в сфере реализации подпрограммы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4250000000',0,'ЦСР_2016',1,'Подпрограмма "Повышение эффективности государственного управления при реализации государственной программы Российской Федерации "Юстиция"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4250100000',0,'ЦСР_2016',1,'Основное мероприятие "Координация и управление реализацией государственной программы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4250200000',0,'ЦСР_2016',1,'Основное мероприятие "Обеспечение выполнения государственных функций"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4250300000',0,'ЦСР_2016',1,'Основное мероприятие "Организация взаимодействия с Гаагской конференцией по международному частному праву"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4260000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие уголовно-исполнительной системы (2007 - 2016 годы)"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4300000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Социально-экономическое развитие Арктической зоны Российской Федерации на период до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4310000000',0,'ЦСР_2016',1,'Подпрограмма "Координация деятельности органов государственной власти в сфере социально-экономического развития Арктической зоны Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4310100000',0,'ЦСР_2016',1,'Основное мероприятие "Координация деятельности федеральных и региональных органов исполнительной власти в части повышения эффективности реализации иных государственных программ Российской Федерации и программ субъектов Российской Федерации на террито',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4310200000',0,'ЦСР_2016',1,'Основное мероприятие "Внедрение механизмов мониторинга и комплексного анализа состояния и перспектив развития ключевых направлений экономики в Арктической зоне Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4400000000',0,'ЦСР_2016',1,'Государственная программа "Развитие оборонно-промышленного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410000000',0,'ЦСР_2016',1,'Подпрограмма "Стимулирование развития оборонно-промышленного комплекса Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410100000',0,'ЦСР_2016',1,'Основное мероприятие "Научно-исследовательские, опытно-конструкторские и технологические работы в целях импортозамещения технологического оборудования и комплектующих изделий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410200000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка в целях импортозамещения технологического оборудования и комплектующих изделий"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410262610',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "ЗВЕЗДА-РЕДУКТОР", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410266890',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в Государственную корпорацию по содействию разработке, производству и экспорту высокотехнологичной промышленной продукции "Ростех" на проведение работ по организации производства импортозамещающих комплектующи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410268540',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Сатурн", г. Рыбинск, Ярославская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410300000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка развития кадрового потенциала оборонно-промышленного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410331010',0,'ЦСР_2016',1,'Стипендии для ученых, конструкторов, технологов и других инженерно-технических работников организаций - исполнителей государственного оборонного заказа за выдающиеся достижения в создании прорывных технологий и разработке современных образцов вооруже',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410331020',0,'ЦСР_2016',1,'Стипендии для специалистов и молодых (до 35 лет включительно) работников организаций - исполнителей государственного оборонного заказа за значительный вклад в создание прорывных технологий и разработку современных образцов вооружения, военной и специ',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410400000',0,'ЦСР_2016',1,'Основное мероприятие "Государственная поддержка в целях обеспечения финансово-экономической устойчивости предприятий оборонно-промышленного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410464210',0,'ЦСР_2016',1,'Субсидии казенным предприятиям оборонно-промышленного комплекса',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410464220',0,'ЦСР_2016',1,'Субсидии стратегическим организациям оборонно-промышленного комплекса в целях предупреждения банкротства',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410464670',0,'ЦСР_2016',1,'Субсидии организациям оборонно-промышленного комплекса на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и государственной корпорации "Банк развития и внешнеэкономической деятельности (Внешэкон',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410464830',0,'ЦСР_2016',1,'Субсидии российским организациям - экспортерам промышленной продукции военного назначения на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешн',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4410466800',0,'ЦСР_2016',1,'Субсидии организациям оборонно-промышленного комплекса - головным исполнителям (исполнителям) государственного оборонного заказа на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие оборонно-промышленного комплекса Российской Федерации на 2011 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062560',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Военно-промышленная корпорация "Научно-производственное объединение машиностроения", г. Реутов, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062570',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Конструкторское бюро химавтоматики", г. Воронеж',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062580',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Научно-производственная корпорация "Системы прецизионного приборостроения", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062610',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "ЗВЕЗДА-РЕДУКТОР", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062620',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Красноярский машиностроительный завод", г. Красноярск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062700',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт молекулярной электроники и завод "Микрон", г. Москва, Зеленоград',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062710',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Концерн "Созвездие", г. Воронеж',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062780',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Концерн "Гранит-Электрон", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062800',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Концерн "Океанприбор", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062870',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Информационные спутниковые системы" имени академика М.Ф. Решетнёва", г. Железногорск, Красноярский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062880',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт полупроводниковых приборов", г. Томск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062900',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Концерн воздушно-космической обороны "Алмаз-Антей", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062910',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт физических измерений", г. Пенза',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062920',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Российская корпорация ракетно-космического приборостроения и информационных систем", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062930',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт точных приборов", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420062940',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение измерительной техники", г. Королев, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063090',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Калугаприбор", г. Калуга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063130',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Ордена Трудового Красного Знамени научно-исследовательский институт автоматической аппаратуры им. академика В.С. Семенихина", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063180',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Федеральный научно-производственный центр "Нижегородский научно-исследовательский приборостроительный институт "Кварц" имени А.П. Горшкова", г. Нижний Новгород',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063190',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Пензенское производственное объединение "Электроприбор", г. Пенза',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063350',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Концерн "Центральный научно-исследовательский институт "Электроприбор", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063460',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Красногорский завод им. С.А. Зверева", г. Красногорск, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063490',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Турбонасос", г. Воронеж',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063510',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Геофизика-Космос", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063520',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт командных приборов", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063590',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Ракетно-космический центр "Прогресс", г. Самара',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063600',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение автоматики имени академика Н.А. Семихатова", г. Екатеринбург, Свердловская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063670',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Северное машиностроительное предприятие", г. Северодвинск, Архангельская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063680',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Центр технологии судостроения и судоремонта", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063690',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Центр судоремонта "Звездочка", г. Северодвинск, Архангельская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063710',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Зеленодольское проектно-конструкторское бюро", г. Зеленодольск, Республика Татарстан (Татарстан)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063720',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательское проектно-технологическое бюро "Онега", г. Северодвинск, Архангельская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063730',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Центральное конструкторское бюро морской техники "Рубин", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063870',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Дальневосточный завод "Звезда", г. Большой Камень, Приморский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063910',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Корпорация "Росхимзащита", г. Тамбов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420063920',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Казанский химический научно-исследовательский институт", г. Казань, Республика Татарстан (Татарстан)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420064040',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "НПО "Энергомаш" имени академика В.П. Глушко", г. Химки, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420064200',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Радиосвязь", г. Красноярск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065210',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Баррикады", г. Волгоград',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065220',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Воткинский завод", г. Воткинск, Удмуртская Республика',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065230',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Специальное конструкторское бюро "Турбина", г. Челябинск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065250',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Уральский научно-исследовательский институт композиционных материалов", г. Пермь',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065300',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт двигателей", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065320',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Ростовский оптико-механический завод", г. Ростов, Ярославская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065350',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт материалов", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065360',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Федеральный научно-производственный центр "Научно-исследовательский институт прикладной химии", г. Сергиев Посад, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065370',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Государственный научно-исследовательский институт машиностроения имени В.В. Бахирева", г. Дзержинск, Нижегородская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065380',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Федеральный научно-производственный центр "Алтай", г. Бийск, Алтайский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065390',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Муромский приборостроительный завод", г. Муром, Владимирская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065430',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Прибалтийский судостроительный завод "Янтарь", г. Калининград',0,'',0,'','', '19000101',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 '4420065440',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Адмиралтейские верфи", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065450',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Средне-Невский судостроительный завод", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065460',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Хабаровский судостроительный завод", г. Хабаровск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065470',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Северное производственное объединение "АРКТИКА", г. Северодвинск, Архангельская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065490',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "АМЗ-НП", г. Арзамас, Нижегородская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065500',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Санкт-Петербургское морское бюро машиностроения "Малахит", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065530',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт электромеханики", г. Истра, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065540',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Государственный ракетный центр имени академика В.П. Макеева", г. Миасс, Челябинская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065570',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт морской теплотехники", г. Ломоносов, г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065610',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Информационные телекоммуникационные технологии", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065680',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт "Электрон", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065720',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "15 центральный автомобильный ремонтный завод", г. Новосибирск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065730',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "514 Авиационный ремонтный завод", г. Ржев, Тверская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065740',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Спецтехника", ЗАТО Озерный, Тверская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065750',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Хабаровский радиотехнический завод", г. Хабаровск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065760',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Ремонтный завод радиоэлектронной техники "Луч", п. Янино, Ленинградская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065770',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Арамильский авиационный ремонтный завод", г. Арамиль, Свердловская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065780',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "9 центральный автомобильный ремонтный завод", г. Энгельс, Саратовская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065790',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "81 бронетанковый ремонтный завод", г. Армавир, Краснодарский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065800',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "60 арсенал", г. Калуга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065820',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "172 центральный автомобильный ремонтный завод", г. Воронеж',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065830',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "163 бронетанковый ремонтный завод", станица Кущевская, Краснодарский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065840',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "570 авиационный ремонтный завод", г. Ейск, Краснодарский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065850',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "103 бронетанковый ремонтный завод", г. пос. Атамановское, Забайкальский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065860',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "360 авиационный ремонтный завод", г. Рязань',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065870',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "144 бронетанковый ремонтный завод", г. Екатеринбург, Свердловская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065880',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "123 авиационный ремонтный завод", г. Старая Русса, Новгородская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065890',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "121 авиационный ремонтный завод", п. Старый городок, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065910',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Воронежский Завод Полупроводниковых Приборов - Сборка", г. Воронеж',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065930',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Корпорация "Московский институт теплотехники", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420065980',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Государственный научно-исследовательский институт "Кристалл", г. Дзержинск, Нижегородская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066000',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Златоустовский машиностроительный завод", г. Златоуст, Челябинская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066010',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Миасский машиностроительный завод", г. Миасс, Челябинская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066040',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственный комплекс "Альтернативная энергетика", г. Электроугли, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066050',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Авангард", г. Сафоново, Смоленская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066060',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Головное особое конструкторское бюро "Прожектор", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066080',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Концерн "Вега", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066090',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Особое конструкторское бюро "Салют", г. Новосибирск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066110',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Протон-Пермские моторы", г. Пермь',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066140',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Стрела", г. Оренбург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066170',0,'ЦСР_2016',1,'Взнос в уставный капитал публичного  акционерного общества "Амурский судостроительный завод", г. Комсомольск-на-Амуре, Хабаровский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066190',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт автоматики и гидравлики", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066200',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Конструкторское бюро точного машиностроения имени А.Э. Нудельмана", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066210',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "33 судоремонтный завод" г. Балтийск, Калининградская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066240',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Калужский электромеханический завод", г. Калуга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066260',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт "Масштаб", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066280',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Кимовский радиоэлектромеханический завод", г. Кимовск, Тульская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066300',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Импульс", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066310',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт оптико-электронного приборостроения", г. Сосновый Бор, Ленинградская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066370',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро "Геофизика", г. Красноярск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066380',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Центральное конструкторско-технологическое бюро полимерных материалов с опытным производством", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066390',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Корпорация космических систем специального назначения "Комета", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066400',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Краснознаменец", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066450',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Корпорация "Тактическое ракетное вооружение", г. Королев, Московская область, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066490',0,'ЦСР_2016',1,'Взнос в уставный капитал   акционерного общества "Системы управления", г. Москва, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066500',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Концерн "Созвездие", г. Воронеж, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066510',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Концерн воздушно-космической обороны "Алмаз-Антей", г. Москва, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066530',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Уфимский завод микроэлектроники "Магнетрон", г. Уфа, Республика Башкортостан',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066540',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Научно-производственное предприятие "Сигнал", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066550',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Ярославский радиозавод", г. Ярославль',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066660',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Корпорация "Тактическое ракетное вооружение", г. Королев, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066680',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в Государственную корпорацию по содействию разработке, производству и экспорту высокотехнологичной промышленной продукции "Ростех" в целях осуществления капитальных вложений организациями, акции (доли) которых',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066810',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Темп" им. Ф. Короткова", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066850',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Специальное конструкторско-технологическое бюро по электрохимии с опытным заводом", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066880',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Северо-Восточный ремонтный центр", г. Вилючинск, Камчатский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066930',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Научно-исследовательский институт "Вектор", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420066960',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Ракетно-космическая корпорация "Энергия" имени С.П. Королева", г. Королев, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420067010',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Завод "Красное Сормово", г. Нижний Новгород',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420067020',0,'ЦСР_2016',1,'Взнос в уставный капитал публичного  акционерного общества "Варяг", г. Владивосток, Приморский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420067030',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Волгоградский металлургический завод "Красный Октябрь", г. Волгоград',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420067040',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Пролетарский завод", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420067790',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-производственное предприятие "Квант", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420067820',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "КУЗНЕЦОВ", г. Самара',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420067860',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Корпорация "Стратегические пункты управления", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420067870',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро транспортного машиностроения", г. Тверь',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420068100',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Особое конструкторское бюро кабельной промышленности", г. Мытищи, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420068130',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Пермская научно-производственная приборостроительная компания", г. Пермь',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4420068140',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "ГЕЛИЙМАШ", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440000000',0,'ЦСР_2016',1,'Подпрограмма "Развитие технологической и производственной базы организаций оборонно-промышленного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440100000',0,'ЦСР_2016',1,'Основное мероприятие "Инновационное технологическое развитие оборонно-промышленного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440200000',0,'ЦСР_2016',1,'Основное мероприятие "Модернизация производственных мощностей организаций оборонно-промышленного комплекса"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440262580',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-производственная корпорация "Системы прецизионного приборостроения", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440262680',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-производственное предприятие "Исток" имени А.И. Шокина",г. Фрязино, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440262710',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Концерн "Созвездие", г. Воронеж',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440262780',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Концерн "Гранит-Электрон", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440262800',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Концерн "Океанприбор", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440263060',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-производственное объединение "Радиоэлектроника" имени В.И. Шимко", г. Казань, Республика Татарстан (Татарстан)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440263090',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Калугаприбор", г. Калуга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440263130',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Ордена Трудового Красного Знамени научно-исследовательский институт автоматической аппаратуры им. академика В.С. Семенихина", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440263190',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Пензенское производственное объединение "Электроприбор", г. Пенза',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440263350',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Концерн "Центральный научно-исследовательский институт "Электроприбор", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440263430',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Государственный Рязанский приборный завод", г. Рязань',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440263440',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Корпорация "Фазотрон - Научно-исследовательский институт радиостроения", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440263670',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Северное машиностроительное предприятие", г. Северодвинск, Архангельская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440263680',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Центр технологии судостроения и судоремонта", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440263690',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Центр судоремонта "Звездочка", г. Северодвинск, Архангельская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440263730',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Центральное конструкторское бюро морской техники "Рубин", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440263920',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Казанский химический научно-исследовательский институт", г. Казань, Республика Татарстан (Татарстан)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440265160',0,'ЦСР_2016',1,'Взнос в уставный капитал публичного акционерного общества "Авиационная холдинговая компания "Сухой", г. Москва',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440265230',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Специальное конструкторское бюро "Турбина", г. Челябинск',0,'',0,'','', '19000101',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 '4440265280',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Завод № 9", г. Екатеринбург, Свердловская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440265370',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Государственный научно-исследовательский институт машиностроения имени В.В. Бахирева", г. Дзержинск, Нижегородская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440265380',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Федеральный научно-производственный центр "Алтай", г. Бийск, Алтайский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440265430',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Прибалтийский судостроительный завод "Янтарь", г. Калининград',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440265440',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Адмиралтейские верфи", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440265480',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Зеленодольский завод имени А.М. Горького", г. Зеленодольск, Республика Татарстан (Татарстан)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440266160',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества Судостроительный завод "Северная верфь", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440266170',0,'ЦСР_2016',1,'Взнос в уставный капитал публичного акционерного общества "Амурский судостроительный завод", г. Комсомольск-на-Амуре, Хабаровский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440266430',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Пензенский научно-исследовательский электротехнический институт", г. Пенза',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440266450',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Корпорация "Тактическое ракетное вооружение", г. Королев, Московская область, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440266490',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Системы управления", г. Москва, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440266500',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Концерн "Созвездие", г. Воронеж, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440266510',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Концерн воздушно-космической обороны "Алмаз-Антей", г. Москва, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440266540',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-производственное предприятие "Сигнал", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440266660',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Корпорация "Тактическое ракетное вооружение", г. Королев, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440266680',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в Государственную корпорацию по содействию разработке, производству и экспорту высокотехнологичной промышленной продукции "Ростех" в целях осуществления  капитальных вложений организациями, акции (доли) которы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440266820',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Каменск-Уральский литейный завод", г. Каменск-Уральский, Свердловская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440266930',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-исследовательский институт "Вектор", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440267020',0,'ЦСР_2016',1,'Взнос в уставный капитал публичного  акционерного общества "Варяг", г. Владивосток, Приморский край',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440267040',0,'ЦСР_2016',1,'Взнос в уставный капитал  акционерного общества "Пролетарский завод", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440267620',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в Государственную корпорацию по содействию разработке, производству и экспорту высокотехнологичной промышленной продукции "Ростех" с целью последующего взноса в уставный капитал акционерного общества "Объедине',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268800',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Калужский завод радиотехнической аппаратуры", г. Жуков, Калужская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268801',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-исследовательский институт "Экран", г. Самара',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268802',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Конструкторское бюро по радиоконтролю систем управления, навигации и связи", г. Ростов-на-Дону, Ростовская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268803',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Калужский научно-исследовательский радиотехнический институт", г. Жуков, Калужская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268804',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-производственное объединение "Квант", г. Великий Новгород',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268805',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Радиозавод",               г. Пенза',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268806',0,'ЦСР_2016',1,'Взнос в уставный капитал Ордена Почета открытого акционерного общества "Телемеханика", г. Нальчик, Кабардино-Балкарская Республика',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268807',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Серовский механический завод", г. Серов, Свердловская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268808',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Конструкторское бюро приборостроения им. академика А.Г. Шипунова", г. Тула',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268809',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "СПЛАВ", г. Тула',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268810',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Вологодский оптико-механический завод", г. Вологда',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268811',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Швабе", г. Екатеринбург, Свердловская область, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268812',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Серпуховский завод "Металлист", г. Серпухов, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268813',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-исследовательский институт электронных приборов", г. Новосибирск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268814',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Краснозаводский химический завод", г. Краснозаводск, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268815',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-производственный концерн "Технологии машиностроения", г. Москва, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268816',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Центральный научно-исследовательский институт точного машиностроения", г. Климовск, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268820',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Вертолеты России", г. Москва, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268821',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Ленинградский механический завод имени Карла Либкнехта", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268822',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Уфимское приборостроительное производственное объединение", г. Уфа, Республика Башкортостан',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268823',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Ульяновское конструкторское бюро приборостроения", г. Ульяновск, Ульяновская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268824',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Корпорация "Росхимзащита", г. Тамбов, Тамбовская область, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268830',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Утес", г. Ульяновск',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268831',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Объединенная судостроительная корпорация", г. Санкт-Петербург, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268832',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Раменский приборостроительный завод", г. Раменское, Московская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268833',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Радиоприбор", г. Казань, Республика Татарстан (Татарстан)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268834',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Завод "Пластмасс", г. Копейск, Челябинская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268835',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Научно-исследовательский институт синтетического волокна с экспериментальным заводом", г. Тверь',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268836',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Объединенная двигателестроительная корпорация", г. Москва, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268837',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Технодинамика", г. Москва, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268838',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "Центральный научно-исследовательский институт "Буревестник", г. Нижний Новгород',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440268839',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "НПО "Высокоточные комплексы", г. Москва, с целью осуществления капитальных вложений дочерними (зависимыми) хозяйственными обществами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440300000',0,'ЦСР_2016',1,'Основное мероприятие "Создание отечественной электронной компонентной базы, используемой при производстве вооружений, военной и специальной техники"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440400000',0,'ЦСР_2016',1,'Основное мероприятие "Импортозамещение технологического оборудования и комплектующих изделий для производства вооружений, военной и специальной техники"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440462610',0,'ЦСР_2016',1,'Взнос в уставный капитал акционерного общества "ЗВЕЗДА-РЕДУКТОР", г. Санкт-Петербург',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440466890',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в Государственную корпорацию по содействию разработке, производству и экспорту высокотехнологичной промышленной продукции "Ростех" на проведение работ по организации производства импортозамещающих комплектующи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4440468540',0,'ЦСР_2016',1,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Сатурн", г. Рыбинск, Ярославская область',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4450000000',0,'ЦСР_2016',1,'Подпрограмма "Разработка и организация производства стратегических материалов для обеспечения производства продукции военного назначения"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4450100000',0,'ЦСР_2016',1,'Основное мероприятие "Замещение технологий производства стратегических материалов и их полуфабрикатов, в том числе импортного производства, необходимых для производства приоритетных образцов вооружения, военной и специальной техники"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4450200000',0,'ЦСР_2016',1,'Основное мероприятие "Восстановление технологий производства стратегических материалов и их полуфабрикатов, необходимых для производства приоритетных образцов вооружения, военной и специальной техники"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4450300000',0,'ЦСР_2016',1,'Основное мероприятие "Создание нормативно-методической базы для единой системы оценки воздействия на материалы и элементы конструкций вооружения, военной и специальной техники климатических факторов"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4450400000',0,'ЦСР_2016',1,'Основное мероприятие "Организация малотоннажных производств стратегических, дефицитных и импортозамещающих материалов, включая модернизацию и развитие объектов научной и производственной инфраструктуры"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4500000000',0,'ЦСР_2016',1,'Государственная программа Российской Федерации "Социально-экономическое развитие Крымского федерального округа на период до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4510000000',0,'ЦСР_2016',1,'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Социально-экономическое развитие Крымского федерального округа на период до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4510200000',0,'ЦСР_2016',1,'Основное мероприятие "Нормативное правовое обеспечение социально-экономического развития Крымского федерального округа"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4510300000',0,'ЦСР_2016',1,'Основное мероприятие "Контроль за осуществлением органами государственной власти Республики Крым и г. Севастополя полномочий Российской Федерации, передаваемых им в соответствии с законодательством Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4520000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Социально-экономическое развитие Республики Крым и г. Севастополя до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '4520051880',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий федеральной целевой программы "Социально-экономическое развитие Республики Крым и г. Севастополя до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7100000000',0,'ЦСР_2016',1,'Развитие пенсионной системы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7100030010',0,'ЦСР_2016',1,'Пенсии военнослужащим, членам их семей и лицам, приравненным к ним по пенсионному обеспечению, а также пособия и иные выплаты в рамках пенсионного обеспечения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7100030560',0,'ЦСР_2016',1,'Материальное обеспечение специалистов ядерного оружейного комплекса Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7100030600',0,'ЦСР_2016',1,'Выплата пенсий по государственному пенсионному обеспечению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7100030610',0,'ЦСР_2016',1,'Выплата доплат к пенсиям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7100031070',0,'ЦСР_2016',1,'Выплата пенсии некоторым категориям граждан Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7100051830',0,'ЦСР_2016',1,'Валоризация величины расчетного пенсионного капитала',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7100051840',0,'ЦСР_2016',1,'Возмещение расходов по выплате страховых пенсий в связи с зачетом в страховой стаж нестраховых периодов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7100051850',0,'ЦСР_2016',1,'Софинансирование формирования пенсионных накоплений застрахованных лиц за счет средств Фонда национального благосостояния',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7100051860',0,'ЦСР_2016',1,'Компенсация выпадающих доходов бюджету Пенсионного фонда Российской Федерации в связи с установлением пониженных тарифов страховых взносов на обязательное пенсионное страхование',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7100052060',0,'ЦСР_2016',1,'Межбюджетные трансферты на обязательное пенсионное страхование',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7300000000',0,'ЦСР_2016',1,'Непрограммные направления деятельности органов управления государственных внебюджетных фондов Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7310000000',0,'ЦСР_2016',1,'Реализация государственных функций в области социальной политики',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7310035810',0,'ЦСР_2016',1,'Гарантийные взносы в фонд гарантирования пенсионных накоплений, уплачиваемые Пенсионным фондом Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7310035820',0,'ЦСР_2016',1,'Передача средств пенсионных накоплений в негосударственные пенсионные фонды',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7320000000',0,'ЦСР_2016',1,'Выполнение функций аппаратами государственных внебюджетных фондов Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7350000000',0,'ЦСР_2016',1,'Международное сотрудничество',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7360000000',0,'ЦСР_2016',1,'Строительство объектов социального и производственного комплексов, в том числе объектов общегражданского назначения, жилья, инфраструктуры',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370000000',0,'ЦСР_2016',1,'Социальные выплаты',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370030560',0,'ЦСР_2016',1,'Материальное обеспечение специалистов ядерного оружейного комплекса Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370030580',0,'ЦСР_2016',1,'Выплата страховой пенсии',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370030590',0,'ЦСР_2016',1,'Выплата накопительной пенсии',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370030600',0,'ЦСР_2016',1,'Выплата пенсий по государственному пенсионному обеспечению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370030610',0,'ЦСР_2016',1,'Выплата доплат к пенсиям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370030620',0,'ЦСР_2016',1,'Доплата к пенсии членам летных экипажей воздушных судов гражданской авиации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370030630',0,'ЦСР_2016',1,'Единовременная выплата средств пенсионных накоплений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370030640',0,'ЦСР_2016',1,'Срочная пенсионная выплата',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370030650',0,'ЦСР_2016',1,'Выплата пенсий, назначенных досрочно гражданам, признанным безработными',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370030660',0,'ЦСР_2016',1,'Доплаты к пенсии работникам организаций угольной промышленности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370031070',0,'ЦСР_2016',1,'Выплата пенсии некоторым категориям граждан Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370031160',0,'ЦСР_2016',1,'Осуществление пенсионного обеспечения отдельных категорий граждан Российской Федерации, проживающих на территориях Республики Крым и города федерального значения Севастополя',0,'',0,'','', '19000101',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 '7370039500',0,'ЦСР_2016',1,'Выплаты правопреемникам умерших застрахованных лиц',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370039510',0,'ЦСР_2016',1,'Выплата пенсий, назначенных Эстонской Республикой',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370039520',0,'ЦСР_2016',1,'Выплата пенсий и иных социальных выплат, назначенных Латвийской Республикой',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370039530',0,'ЦСР_2016',1,'Выплата пенсий и иных социальных выплат, назначенных Республикой Беларусь',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370039540',0,'ЦСР_2016',1,'Выплата пенсий и иных социальных выплат, назначенных Республикой Болгария',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7370039550',0,'ЦСР_2016',1,'Выплата пенсий, назначенных Литовской Республикой',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7380000000',0,'ЦСР_2016',1,'Иные мероприятия',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7380054000',0,'ЦСР_2016',1,'Дотация на сбалансированность, передаваемая федеральному бюджету из бюджета Федерального фонда обязательного медицинского страхования',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7700000000',0,'ЦСР_2016',1,'Обеспечение функционирования Президента Российской Федерации и его администрации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7710000000',0,'ЦСР_2016',1,'Президент Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7720000000',0,'ЦСР_2016',1,'Администрация Президента Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7800000000',0,'ЦСР_2016',1,'Обеспечение функционирования Председателя Правительства Российской Федерации и его заместителей, Аппарата Правительства Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7810000000',0,'ЦСР_2016',1,'Председатель Правительства Российской Федерации и его заместители',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '7820000000',0,'ЦСР_2016',1,'Аппарат Правительства Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8800000000',0,'ЦСР_2016',1,'Следственный комитет Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8890000000',0,'ЦСР_2016',1,'Обеспечение функционирования Следственного комитета Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8890030340',0,'ЦСР_2016',1,'Ежемесячная доплата к пенсиям отдельным категориям пенсионеров в соответствии с Указом Президента Российской Федерации от 18 февраля 2005 года № 176 "Об установлении ежемесячной доплаты к пенсиям отдельным категориям пенсионеров"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8890030450',0,'ЦСР_2016',1,'Пособие детям погибших (умерших) или пропавших без вести в связи с исполнением служебных обязанностей сотрудников следственных органов Следственного комитета Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8900000000',0,'ЦСР_2016',1,'Обеспечение деятельности отдельных федеральных государственных органов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8920000000',0,'ЦСР_2016',1,'Обеспечение визитов делегаций высших органов власти за рубеж',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8930000000',0,'ЦСР_2016',1,'Общественная палата Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990000000',0,'ЦСР_2016',1,'Управление делами Президента Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990020920',0,'ЦСР_2016',1,'Финансовое обеспечение деятельности Уполномоченного при Президенте Российской Федерации по защите прав предпринимателей',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990030330',0,'ЦСР_2016',1,'Государственные премии Российской Федерации в области науки и техники, образования и культуры в соответствии с Указом Президента Российской Федерации от 21 июня 2004 года № 785 "О совершенствовании системы государственного премирования за достижения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990030370',0,'ЦСР_2016',1,'Государственная премия Российской Федерации за выдающиеся достижения в области гуманитарной деятельности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990030400',0,'ЦСР_2016',1,'Премия Президента Российской Федерации в области науки и инноваций для молодых ученых',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990030430',0,'ЦСР_2016',1,'Премии Президента Российской Федерации для молодых деятелей культуры',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990031110',0,'ЦСР_2016',1,'Государственные премии Российской Федерации за выдающиеся достижения в области правозащитной и благотворительной деятельности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990031130',0,'ЦСР_2016',1,'Премии Президента Российской Федерации в области литературы и искусства за произведения для детей и юношества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990060500',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "Аналитический центр при Правительстве Российской Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990062160',0,'ЦСР_2016',1,'Субсидии на поддержку некоммерческих неправительственных организаций, участвующих в развитии институтов гражданского общества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990062220',0,'ЦСР_2016',1,'Субсидии центрам исторического наследия президентов Российской Федерации, прекративших исполнение своих полномочий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990064060',0,'ЦСР_2016',1,'Субсидии организациям на возмещение расходов по обеспечению содержания и эксплуатации объектов федерального недвижимого имущества, расположенного за пределами территории Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '8990064090',0,'ЦСР_2016',1,'Субсидии федеральным государственным унитарным предприятиям, находящимся в ведении Управления делами Президента Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9000000000',0,'ЦСР_2016',1,'Государственная судебная власть',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9010000000',0,'ЦСР_2016',1,'Председатель Конституционного Суда Российской Федерации и судьи Конституционного Суда Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9020000000',0,'ЦСР_2016',1,'Председатель Верховного Суда Российской Федерации и судьи Верховного Суда Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9040000000',0,'ЦСР_2016',1,'Судьи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9050000000',0,'ЦСР_2016',1,'Судебный департамент при Верховном Суде Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9060000000',0,'ЦСР_2016',1,'Аппараты судов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9090000000',0,'ЦСР_2016',1,'Реализация функций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9090051200',0,'ЦСР_2016',1,'Субвенции на осуществление полномочий по составлению (изменению) списков кандидатов в присяжные заседатели федеральных судов общей юрисдикции в Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9100000000',0,'ЦСР_2016',1,'Прокуратура Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9190000000',0,'ЦСР_2016',1,'Обеспечение деятельности Прокуратуры Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9190030340',0,'ЦСР_2016',1,'Ежемесячная доплата к пенсиям отдельным категориям пенсионеров в соответствии с Указом Президента Российской Федерации от 18 февраля 2005 года № 176 "Об установлении ежемесячной доплаты к пенсиям отдельным категориям пенсионеров"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9190030410',0,'ЦСР_2016',1,'Пособие детям погибших (пропавших без вести) работников органов прокуратуры',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9200000000',0,'ЦСР_2016',1,'Уполномоченный по правам человека в Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9290000000',0,'ЦСР_2016',1,'Обеспечение деятельности Уполномоченного по правам человека в Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9300000000',0,'ЦСР_2016',1,'Счетная палата Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9390000000',0,'ЦСР_2016',1,'Обеспечение деятельности Счетной палаты Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9400000000',0,'ЦСР_2016',1,'Центральная избирательная комиссия Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9420000000',0,'ЦСР_2016',1,'Проведение референдумов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9430000000',0,'ЦСР_2016',1,'Проведение выборов Президента Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9440000000',0,'ЦСР_2016',1,'Проведение выборов депутатов Государственной Думы Федерального Собрания Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9490000000',0,'ЦСР_2016',1,'Обеспечение деятельности Центральной избирательной комиссии Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9500000000',0,'ЦСР_2016',1,'Совет Федерации Федерального Собрания Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9520000000',0,'ЦСР_2016',1,'Члены Совета Федерации и их помощники',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9520051420',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на обеспечение членов Совета Федерации и их помощников в субъектах Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9590000000',0,'ЦСР_2016',1,'Обеспечение деятельности Совета Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9590060820',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "Редакция Телеканала Совета Федерации"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9590062440',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "Парламентская газета"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9600000000',0,'ЦСР_2016',1,'Государственная Дума Федерального Собрания  Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9620000000',0,'ЦСР_2016',1,'Депутаты Государственной Думы и их помощники',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9620051410',0,'ЦСР_2016',1,'Иные межбюджетные трансферты на обеспечение деятельности депутатов Государственной Думы и их помощников в избирательных округах',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9690000000',0,'ЦСР_2016',1,'Обеспечение деятельности Государственной Думы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9690062440',0,'ЦСР_2016',1,'Субсидии автономной некоммерческой организации "Парламентская газета"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9700000000',0,'ЦСР_2016',1,'Государственная корреспонденция',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9790000000',0,'ЦСР_2016',1,'Обеспечение доставки',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9800000000',0,'ЦСР_2016',1,'Главное управление специальных программ Президента Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9890000000',0,'ЦСР_2016',1,'Обеспечение деятельности Главного управления специальных программ Президента Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9890030020',0,'ЦСР_2016',1,'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9890030140',0,'ЦСР_2016',1,'Возмещение федеральными органами исполнительной власти расходов на погребение',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9890030170',0,'ЦСР_2016',1,'Пособия, выплаты и компенсации членам семей военнослужащих, а также лицам, уволенным с военной службы без права на пенсию',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9890030240',0,'ЦСР_2016',1,'Пособия и компенсации членам семей погибших (умерших) военнослужащих (граждан, проходивших военные сборы, инвалидов вследствие военной травмы), а также лицам, которым установлена инвалидность вследствие военной травмы после увольнения с военной служб',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9900000000',0,'ЦСР_2016',1,'Реализация функций иных федеральных органов государственной власти',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9910000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие судебной системы России на 2013 - 2020 годы"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9910035830',0,'ЦСР_2016',1,'Субсидии на приобретение жилых помещений работникам аппаратов судов и Судебного департамента при Верховном Суде Российской Федерации и его территориальных органов, нуждающимся в улучшении жилищных условий',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9920000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Создание системы базирования Черноморского флота на территории Российской Федерации в 2005 - 2020 годах"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9940000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Промышленная утилизация вооружения и военной техники на 2011 - 2015 годы и на период до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9980000000',0,'ЦСР_2016',1,'Федеральная целевая программа "Развитие Республики Карелия на период до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9980054190',0,'ЦСР_2016',1,'Субсидии на реализацию мероприятий федеральной целевой программы "Развитие Республики Карелия на период до 2020 года"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990000000',0,'ЦСР_2016',1,'Иные непрограммные мероприятия',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990020990',0,'ЦСР_2016',1,'Финансовое обеспечение мероприятий по дополнительной поддержке отраслей экономики, социальной поддержке граждан и оказанию гуманитарной помощи населению иностранных государств по решениям Правительства Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990030020',0,'ЦСР_2016',1,'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990030030',0,'ЦСР_2016',1,'Пособие по уходу за ребенком гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации вслед',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990030040',0,'ЦСР_2016',1,'Компенсация в возмещение вреда гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации всл',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990030140',0,'ЦСР_2016',1,'Возмещение федеральными органами исполнительной власти расходов на погребение',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990030240',0,'ЦСР_2016',1,'Пособия и компенсации членам семей погибших (умерших) военнослужащих (граждан, проходивших военные сборы, инвалидов вследствие военной травмы), а также лицам, которым установлена инвалидность вследствие военной травмы после увольнения с военной служб',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990049900',0,'ЦСР_2016',1,'Мероприятия, осуществляемые на основании отдельных решений Президента Российской Федерации и Правительства Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990051180',0,'ЦСР_2016',1,'Субвенции на осуществление первичного воинского учета на территориях, где отсутствуют военные комиссариаты',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990051600',0,'ЦСР_2016',1,'Иные межбюджетные трансферты, передаваемые для компенсации дополнительных расходов, возникших в результате решений, принятых органами власти другого уровня',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990052030',0,'ЦСР_2016',1,'Обеспечение сбалансированности бюджета Федерального фонда обязательного медицинского страхования',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990060200',0,'ЦСР_2016',1,'Государственная поддержка политических партий, принимавших участие в выборах, в целях компенсации затрат по их участию',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990062270',0,'ЦСР_2016',1,'Субсидии Общероссийской общественно-государственной организации "Добровольное общество содействия армии, авиации и флоту России"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990062450',0,'ЦСР_2016',1,'Имущественный взнос Российской Федерации в некоммерческую организацию "Фонд перспективных исследований"',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990067090',0,'ЦСР_2016',1,'Субсидии организациям оборонно-промышленного комплекса на возмещение затрат на уплату процентов по кредитам, привлекаемым ими для целей выполнения (реализации) Государственной программы вооружения на 2011 - 2020 годы в рамках государственного оборонн',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9990067980',0,'ЦСР_2016',1,'Субсидия открытому акционерному обществу "Телерадиокомпания Вооруженных Сил Российской Федерации "ЗВЕЗДА"',0,'',0,'','', '19000101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'ЦСР_2016'

GO

exec RN_SAVE_REPORT_KBK 0,'ВР_2011',0,'Виды расходов','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='SHARED_2011' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'ВР_2011',@link_self,'Виды расходов','HEADER'
GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'000',@link_self,'Неизвестный вид расходов','ВР_2011',0,'',0,'','Неизвестный вид расходов',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'001',@link_self,'Выполнение функций бюджетными учреждениями','ВР_2011',0,'',0,'','Выполнение функций бюджетными учреждениями',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'002',@link_self,'Трансферты бюджету Фонда социального страхования Российской Федерации','ВР_2011',0,'',0,'','Трансферты бюджету Фонда социального страхования Российской Федерации',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'003',@link_self,'Бюджетные инвестиции','ВР_2011',0,'',0,'','Бюджетные инвестиции',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'004',@link_self,'Трансферты бюджету Пенсионного фонда Российской Федерации','ВР_2011',0,'',0,'','Трансферты бюджету Пенсионного фонда Российской Федерации',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'005',@link_self,'Социальные выплаты','ВР_2011',0,'',0,'','Социальные выплаты',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'006',@link_self,'Субсидии юридическим лицам','ВР_2011',0,'',0,'','Субсидии юридическим лицам',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'007',@link_self,'Прочие дотации','ВР_2011',0,'',0,'','Прочие дотации',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'008',@link_self,'Фонд финансовой поддержки','ВР_2011',0,'',0,'','Фонд финансовой поддержки',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'009',@link_self,'Фонд компенсаций','ВР_2011',0,'',0,'','Фонд компенсаций',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'010',@link_self,'Фонд софинансирования','ВР_2011',0,'',0,'','Фонд софинансирования',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'011',@link_self,'Выполнение международных обязательств','ВР_2011',0,'',0,'','Выполнение международных обязательств',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'012',@link_self,'Выполнение функций государственными органами','ВР_2011',0,'',0,'','Выполнение функций государственными органами',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'013',@link_self,'Прочие расходы','ВР_2011',0,'',0,'','Прочие расходы',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'014',@link_self,'Функционирование органов в сфере национальной безопасности, правоохранительной деятельности и обороны','ВР_2011',0,'',0,'','Функционирование органов в сфере национальной безопасности, правоохранительной деятельности и обороны',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'015',@link_self,'Научно-исследовательские и опытно-конструкторские работы','ВР_2011',0,'',0,'','Научно-исследовательские и опытно-конструкторские работы',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'016',@link_self,'Трансферты бюджету Федерального фонда обязательного медицинского страхования','ВР_2011',0,'',0,'','Трансферты бюджету Федерального фонда обязательного медицинского страхования',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'017',@link_self,'Иные межбюджетные трансферты','ВР_2011',0,'',0,'','Иные межбюджетные трансферты',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'018',@link_self,'Иные субсидии','ВР_2011',0,'',0,'','Иные субсидии',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'019',@link_self,'Субсидии некоммерческим организациям','ВР_2011',0,'',0,'','Субсидии некоммерческим организациям',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'020',@link_self,'Софинансирование объектов капитального строительства государственной собственности субъектов Российской Федерации (объектов капитального строительства собственности муниципальных образований)','ВР_2011',0,'',0,'','Софинансирование объектов капитального строительства государственной собственности субъектов Российской Федерации (объектов капитального строительства собственности муниципальных образований)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'022',@link_self,'Мероприятия в сфере образования','ВР_2011',0,'',0,'','Мероприятия в сфере образования',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'023',@link_self,'Мероприятия по поддержке и развитию культуры, искусства, кинематографии, средств массовой информации и архивного дела','ВР_2011',0,'',0,'','Мероприятия по поддержке и развитию культуры, искусства, кинематографии, средств массовой информации и архивного дела',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'026',@link_self,'Компенсация части затрат на приобретение средств химизации','ВР_2011',0,'',0,'','Компенсация части затрат на приобретение средств химизации',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'027',@link_self,'Совершенствование программного и методического обеспечения осуществления государственной радиационно-эпидемиологической регистрации граждан на федеральном и региональном уровнях и актуализация Национального регистра','ВР_2011',0,'',0,'','Совершенствование программного и методического обеспечения осуществления государственной радиационно-эпидемиологической регистрации граждан на федеральном и региональном уровнях и актуализация Национального регистра',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'028',@link_self,'Обеспечение доступности информации по проблемам преодоления последствий радиационных катастроф и инцидентов, разработка и продвижение информационных проектов по формированию адекватного восприятия гражданами возможных угроз жизнедеятельности и снижен','ВР_2011',0,'',0,'','Обеспечение доступности информации по проблемам преодоления последствий радиационных катастроф и инцидентов, разработка и продвижение информационных проектов по формированию адекватного восприятия гражданами возможных угроз жизнедеятельности и снижению уровня социально-психологической напряженности',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'029',@link_self,'Создание условий для реализации информационной политики и внедрения современных технологий на загрязненных территориях','ВР_2011',0,'',0,'','Создание условий для реализации информационной политики и внедрения современных технологий на загрязненных территориях',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'030',@link_self,'Обеспечение выполнения международных обязательств Российской Федерации в области преодоления последствий радиационных катастроф и инцидентов','ВР_2011',0,'',0,'','Обеспечение выполнения международных обязательств Российской Федерации в области преодоления последствий радиационных катастроф и инцидентов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'032',@link_self,'Совершенствование системы мониторинга и прогнозирования чрезвычайных ситуаций, в том числе обусловленных сейсмической опасностью и цунами','ВР_2011',0,'',0,'','Совершенствование системы мониторинга и прогнозирования чрезвычайных ситуаций, в том числе обусловленных сейсмической опасностью и цунами',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'039',@link_self,'Финансирование расходов, осуществляемое за счет средств, поступающих от сдачи в аренду имущества, закрепленного за государственными организациями','ВР_2011',0,'',0,'','Финансирование расходов, осуществляемое за счет средств, поступающих от сдачи в аренду имущества, закрепленного за государственными организациями',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'040',@link_self,'Специальные мероприятия','ВР_2011',0,'',0,'','Специальные мероприятия',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'043',@link_self,'Ликвидация и вывод из эксплуатации ядерно и радиационно опасных объектов, наземных стратегических ракетных комплексов и объектов хранения, производства и уничтожения оружия','ВР_2011',0,'',0,'','Ликвидация и вывод из эксплуатации ядерно и радиационно опасных объектов, наземных стратегических ракетных комплексов и объектов хранения, производства и уничтожения оружия',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'044',@link_self,'Уничтожение запасов химического оружия','ВР_2011',0,'',0,'','Уничтожение запасов химического оружия',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'046',@link_self,'Мероприятия, связанные с реализацией задач по утилизации и ликвидации вооружения, военной техники, иного производственно-технического оборудования и имущества, уничтожению запасов химического оружия','ВР_2011',0,'',0,'','Мероприятия, связанные с реализацией задач по утилизации и ликвидации вооружения, военной техники, иного производственно-технического оборудования и имущества, уничтожению запасов химического оружия',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'047',@link_self,'Инспекционная деятельность','ВР_2011',0,'',0,'','Инспекционная деятельность',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'048',@link_self,'Осуществление прав пользования и распоряжения лесами, их охрана, защита и воспроизводство','ВР_2011',0,'',0,'','Осуществление прав пользования и распоряжения лесами, их охрана, защита и воспроизводство',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'049',@link_self,'Мероприятия в области оборонно-промышленного комплекса','ВР_2011',0,'',0,'','Мероприятия в области оборонно-промышленного комплекса',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'050',@link_self,'Уточнение фактических и прогнозируемых границ зон радиоактивного загрязнения и подготовка карт радиоактивного загрязнения отдельных территорий','ВР_2011',0,'',0,'','Уточнение фактических и прогнозируемых границ зон радиоактивного загрязнения и подготовка карт радиоактивного загрязнения отдельных территорий',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'051',@link_self,'Мероприятия по обеспечению взрывопожаробезопасного состояния систем хранения и эксплуатации специальных объектов','ВР_2011',0,'',0,'','Мероприятия по обеспечению взрывопожаробезопасного состояния систем хранения и эксплуатации специальных объектов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'053',@link_self,'Мероприятия, связанные с реализацией задач по утилизации, включая расходы по реабилитации береговых территорий, транспортировке и переработке отработавшего ядерного топлива','ВР_2011',0,'',0,'','Мероприятия, связанные с реализацией задач по утилизации, включая расходы по реабилитации береговых территорий, транспортировке и переработке отработавшего ядерного топлива',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'054',@link_self,'Мероприятия по землеустройству и землепользованию','ВР_2011',0,'',0,'','Мероприятия по землеустройству и землепользованию',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'055',@link_self,'Закупки специальной космической техники, организация запусков и управление полетами космических аппаратов','ВР_2011',0,'',0,'','Закупки специальной космической техники, организация запусков и управление полетами космических аппаратов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'056',@link_self,'Государственная поддержка космической деятельности в интересах федеральных нужд','ВР_2011',0,'',0,'','Государственная поддержка космической деятельности в интересах федеральных нужд',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'063',@link_self,'Утилизация и ликвидация вооружения и военной техники','ВР_2011',0,'',0,'','Утилизация и ликвидация вооружения и военной техники',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'064',@link_self,'Информатика','ВР_2011',0,'',0,'','Информатика',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'067',@link_self,'Мероприятия в области здравоохранения','ВР_2011',0,'',0,'','Мероприятия в области здравоохранения',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'070',@link_self,'Мероприятия по обеспечению взрывопожаробезопасного состояния систем хранения и эксплуатации специальных объектов (особых базисных складов) хранения взрывчатых материалов','ВР_2011',0,'',0,'','Мероприятия по обеспечению взрывопожаробезопасного состояния систем хранения и эксплуатации специальных объектов (особых базисных складов) хранения взрывчатых материалов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'073',@link_self,'Отдельные мероприятия по другим видам транспорта','ВР_2011',0,'',0,'','Отдельные мероприятия по другим видам транспорта',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'074',@link_self,'Государственная поддержка организаций при выполнении комплекса мероприятий по хранению отработавшего ядерного топлива и радиоактивных отходов, блоков реакторных отсеков и судов атомного технологического обслуживания','ВР_2011',0,'',0,'','Государственная поддержка организаций при выполнении комплекса мероприятий по хранению отработавшего ядерного топлива и радиоактивных отходов, блоков реакторных отсеков и судов атомного технологического обслуживания',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'075',@link_self,'Закупки специальной космической техники для обеспечения функционирования системы ГЛОНАСС','ВР_2011',0,'',0,'','Закупки специальной космической техники для обеспечения функционирования системы ГЛОНАСС',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'076',@link_self,'Мероприятия в области национальной обороны','ВР_2011',0,'',0,'','Мероприятия в области национальной обороны',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'077',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Объединенная авиастроительная корпорация"','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Объединенная авиастроительная корпорация"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'080',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Федеральная сетевая компания Единой энергетической системы"
','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Федеральная сетевая компания Единой энергетической системы"
',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'082',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "РусГидро"','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "РусГидро"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'083',@link_self,'Взнос в уставный капитал открытого акционерного общества "Росагролизинг"','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Росагролизинг"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'084',@link_self,'Взнос в уставный капитал открытого акционерного общества "Российский сельскохозяйственный банк";
','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Российский сельскохозяйственный банк";
',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'087',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Объединенная судостроительная корпорация"','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Объединенная судостроительная корпорация"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'088',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "РОСНАНО"','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "РОСНАНО"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'089',@link_self,'Взнос в уставный капитал открытого акционерного общества "Особые экономические зоны"','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Особые экономические зоны"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'090',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "РАО Энергетические системы Востока"','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "РАО Энергетические системы Востока"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'092',@link_self,'Утилизация атомных подводных лодок, судов атомного технологического обслуживания, надводных кораблей с ядерными энергетическими установками, плавучих емкостей для хранения жидких радиоактивных отходов','ВР_2011',0,'',0,'','Утилизация атомных подводных лодок, судов атомного технологического обслуживания, надводных кораблей с ядерными энергетическими установками, плавучих емкостей для хранения жидких радиоактивных отходов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'093',@link_self,'Государственная поддержка организаций при выполнении комплекса мероприятий в области утилизации и ликвидации накопленных компонентов ядерных боеприпасов','ВР_2011',0,'',0,'','Государственная поддержка организаций при выполнении комплекса мероприятий в области утилизации и ликвидации накопленных компонентов ядерных боеприпасов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'094',@link_self,'Мероприятия, связанные с созданием и обеспечением функционирования системы геофизического мониторинга','ВР_2011',0,'',0,'','Мероприятия, связанные с созданием и обеспечением функционирования системы геофизического мониторинга',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'095',@link_self,'Мероприятия по повышению безопасности остановленных и функционирующих ядерно и радиационно опасных объектов, включая мероприятия при обращении с накопленными отработавшим ядерным топливом и радиоактивными отходами','ВР_2011',0,'',0,'','Мероприятия по повышению безопасности остановленных и функционирующих ядерно и радиационно опасных объектов, включая мероприятия при обращении с накопленными отработавшим ядерным топливом и радиоактивными отходами',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'096',@link_self,'Мероприятия по созданию систем геодезического и навигационно-картографического обеспечения','ВР_2011',0,'',0,'','Мероприятия по созданию систем геодезического и навигационно-картографического обеспечения',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'098',@link_self,'Развитие инфраструктуры города Мирного','ВР_2011',0,'',0,'','Развитие инфраструктуры города Мирного',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'099',@link_self,'Субсидии на осуществление мероприятий по обеспечению жильем граждан Российской Федерации, проживающих в сельской местности','ВР_2011',0,'',0,'','Субсидии на осуществление мероприятий по обеспечению жильем граждан Российской Федерации, проживающих в сельской местности',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'100',@link_self,'Расходы на выплаты персоналу в целях обеспечения выполнения функций государственными органами, казенными учреждениями, органами управления государственными внебюджетными фондами','ВР_2011',0,'',0,'','Расходы на выплаты персоналу в целях обеспечения выполнения функций государственными органами, казенными учреждениями, органами управления государственными внебюджетными фондами',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Расходы на выплаты персоналу в целях обеспечения выполнения функций государственными органами, казенными учреждениями, органами управления государственными внебюджетными фондами', 'Расходы на выплаты персоналу в целях обеспечения выполнения функций государственными органами, казенными учреждениями, органами управления государственными внебюджетными фондами', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'104',@link_self,'Государственное образовательное учреждение высшего профессионального образования "Северо-Кавказский государственный технический университет", общежитие, г. Ставрополь','ВР_2011',0,'',0,'','Государственное образовательное учреждение высшего профессионального образования "Северо-Кавказский государственный технический университет", общежитие, г. Ставрополь',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'105',@link_self,'Федеральное государственное образовательное учреждение "Всероссийский детский центр "Орленок", жилой дом, пос. Новомихайловский, Туапсинский район, Краснодарский край','ВР_2011',0,'',0,'','Федеральное государственное образовательное учреждение "Всероссийский детский центр "Орленок", жилой дом, пос. Новомихайловский, Туапсинский район, Краснодарский край',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'106',@link_self,'Государственное образовательное учреждение высшего профессионального образования "Дагестанский государственный педагогический университет", общежитие, г. Махачкала, Республика Дагестан','ВР_2011',0,'',0,'','Государственное образовательное учреждение высшего профессионального образования "Дагестанский государственный педагогический университет", общежитие, г. Махачкала, Республика Дагестан',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'108',@link_self,'Федеральное государственное образовательное учреждение высшего профессионального образования "Национальный исследовательский технологический университет "МИСиС", общежитие, г. Москва','ВР_2011',0,'',0,'','Федеральное государственное образовательное учреждение высшего профессионального образования "Национальный исследовательский технологический университет "МИСиС", общежитие, г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'109',@link_self,'Государственное образовательное учреждение высшего профессионального образования для инвалидов с нарушением опорно-двигательной системы "Московский государственный социально-гуманитарный институт", общежитие, г. Москва','ВР_2011',0,'',0,'','Государственное образовательное учреждение высшего профессионального образования для инвалидов с нарушением опорно-двигательной системы "Московский государственный социально-гуманитарный институт", общежитие, г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '100' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'110',@link_self,'Расходы на выплаты персоналу казенных учреждений','ВР_2011',0,'',0,'','Расходы на выплаты персоналу казенных учреждений','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '110' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'111',@link_self,'Фонд оплаты труда казенных учреждений и взносы по обязательному социальному страхованию','ВР_2011',0,'',0,'','Фонд оплаты труда казенных учреждений и взносы по обязательному социальному страхованию','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Фонд оплаты труда и страховые взносы', 'Фонд оплаты труда и страховые взносы', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Фонд оплаты труда казенных учреждений и взносы по обязательному социальному страхованию', 'Фонд оплаты труда казенных учреждений и взносы по обязательному социальному страхованию', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '110' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'112',@link_self,'Иные выплаты персоналу казенных учреждений, за исключением фонда оплаты труда','ВР_2011',0,'',0,'','Иные выплаты персоналу казенных учреждений, за исключением фонда оплаты труда','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты персоналу казенных учреждений, за исключением фонда оплаты труда', 'Иные выплаты персоналу казенных учреждений, за исключением фонда оплаты труда', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты персоналу, за исключением фонда оплаты труда', 'Иные выплаты персоналу, за исключением фонда оплаты труда', '20000101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '110' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'113',@link_self,'Иные выплаты, за исключением фонда оплаты труда казенных учреждений, лицам, привлекаемым согласно законодательству для выполнения отдельных полномочий','ВР_2011',0,'',0,'','Иные выплаты, за исключением фонда оплаты труда казенных учреждений, лицам, привлекаемым согласно законодательству для выполнения отдельных полномочий','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты, за исключением фонда оплаты труда казенных учреждений, лицам, привлекаемым согласно законодательству для выполнения отдельных полномочий', 'Иные выплаты, за исключением фонда оплаты труда казенных учреждений, лицам, привлекаемым согласно законодательству для выполнения отдельных полномочий', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Федеральное государственное автономное образовательное учреждение высшего профессионального образования "Дальневосточный федеральный университет", общежитие, г. Владивосток, Приморский край', 'Федеральное государственное автономное образовательное учреждение высшего профессионального образования "Дальневосточный федеральный университет", общежитие, г. Владивосток, Приморский край', '20000101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'116',@link_self,'Государственное образовательное учреждение высшего профессионального образования "Тверской государственный университет", г. Тверь, 9-этажные общежития № 4 и № 5 с блоком обслуживания по ул. Плеханова, г. Тверь','ВР_2011',0,'',0,'','Государственное образовательное учреждение высшего профессионального образования "Тверской государственный университет", г. Тверь, 9-этажные общежития № 4 и № 5 с блоком обслуживания по ул. Плеханова, г. Тверь',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'117',@link_self,'Государственное образовательное учреждение высшего профессионального образования "Нижегородский государственный технический университет им. Р.Е. Алексеева", комплекс общежитий с блоком обслуживания по Казанскому шоссе в Нижегородском районе г. Нижний','ВР_2011',0,'',0,'','Государственное образовательное учреждение высшего профессионального образования "Нижегородский государственный технический университет им. Р.Е. Алексеева", комплекс общежитий с блоком обслуживания по Казанскому шоссе в Нижегородском районе г. Нижний Новгород (2-я очередь строительства)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '100' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'120',@link_self,'Расходы на выплаты персоналу государственных (муниципальных) органов','ВР_2011',0,'',0,'','Расходы на выплаты персоналу государственных (муниципальных) органов','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Расходы на выплаты персоналу государственных (муниципальных) органов', 'Расходы на выплаты персоналу государственных (муниципальных) органов', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Расходы на выплаты персоналу государственных органов', 'Расходы на выплаты персоналу государственных органов', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '120' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'121',@link_self,'Фонд оплаты труда государственных (муниципальных) органов и взносы по обязательному социальному страхованию','ВР_2011',0,'',0,'','Фонд оплаты труда государственных (муниципальных) органов и взносы по обязательному социальному страхованию','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Фонд оплаты труда государственных (муниципальных) органов и взносы по обязательному социальному страхованию', 'Фонд оплаты труда государственных (муниципальных) органов и взносы по обязательному социальному страхованию', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Фонд оплаты труда и страховые взносы', 'Фонд оплаты труда и страховые взносы', '20000101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '120' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'122',@link_self,'Иные выплаты персоналу государственных (муниципальных) органов, за исключением фонда оплаты труда','ВР_2011',0,'',0,'','Иные выплаты персоналу государственных (муниципальных) органов, за исключением фонда оплаты труда','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты персоналу государственных (муниципальных) органов, за исключением фонда оплаты труда', 'Иные выплаты персоналу государственных (муниципальных) органов, за исключением фонда оплаты труда', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты персоналу, за исключением фонда оплаты труда', 'Иные выплаты персоналу, за исключением фонда оплаты труда', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '100' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'130',@link_self,'Расходы на выплаты персоналу в сфере национальной безопасности, правоохранительной деятельности и обороны','ВР_2011',0,'',0,'','Расходы на выплаты персоналу в сфере национальной безопасности, правоохранительной деятельности и обороны','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '130' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'131',@link_self,'Денежное довольствие военнослужащих и сотрудников, имеющих специальные звания','ВР_2011',0,'',0,'','Денежное довольствие военнослужащих и сотрудников, имеющих специальные звания','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Денежное довольствие военнослужащих и приравненных к ним лиц', 'Денежное довольствие военнослужащих и приравненных к ним лиц', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Денежное довольствие военнослужащих и сотрудников, имеющих специальные звания', 'Денежное довольствие военнослужащих и сотрудников, имеющих специальные звания', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '130' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'133',@link_self,'Расходы на выплаты военнослужащим и сотрудникам, имеющим специальные звания, зависящие от размера денежного довольствия','ВР_2011',0,'',0,'','Расходы на выплаты военнослужащим и сотрудникам, имеющим специальные звания, зависящие от размера денежного довольствия','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Расходы на выплаты военнослужащим и сотрудникам, имеющим специальные звания, зависящие от размера денежного довольствия', 'Расходы на выплаты военнослужащим и сотрудникам, имеющим специальные звания, зависящие от размера денежного довольствия', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Расходы на выплаты, зависящие от размера денежного довольствия', 'Расходы на выплаты, зависящие от размера денежного довольствия', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '130' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'134',@link_self,'Иные выплаты персоналу и сотрудникам, имеющим специальные звания','ВР_2011',0,'',0,'','Иные выплаты персоналу и сотрудникам, имеющим специальные звания','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты персоналу и сотрудникам, имеющим специальные звания', 'Иные выплаты персоналу и сотрудникам, имеющим специальные звания', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Иные выплаты персоналу, за исключением денежного довольствия', 'Иные выплаты персоналу, за исключением денежного довольствия', '20000101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'137',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Стрела", г. Тула
Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Стрела", г. Тула
','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Стрела", г. Тула','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'139',@link_self,'Взнос в уставный капитал открытого акционерного общества "Туламашзавод", г. Тула','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Туламашзавод", г. Тула','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '100' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'140',@link_self,'Расходы на выплаты персоналу государственных внебюджетных фондов','ВР_2011',0,'',0,'','Расходы на выплаты персоналу государственных внебюджетных фондов','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '140' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'141',@link_self,'Фонд оплаты труда и страховые взносы','ВР_2011',0,'',0,'','Фонд оплаты труда и страховые взносы','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '140' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'142',@link_self,'Иные выплаты персоналу, за исключением фонда оплаты труда','ВР_2011',0,'',0,'','Иные выплаты персоналу, за исключением фонда оплаты труда','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'164',@link_self,'Взнос в уставный капитал открытого акционерного общества "НИИ молекулярной электроники и завод "Микрон", г. Москва, Зеленоград','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "НИИ молекулярной электроники и завод "Микрон", г. Москва, Зеленоград',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'167',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт "Электрон", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт "Электрон", г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'169',@link_self,'Взнос в уставный капитал открытого акционерного общества "Военно-промышленная корпорация "Научно-производственное объединение машиностроения", г. Реутов, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Военно-промышленная корпорация "Научно-производственное объединение машиностроения", г. Реутов, Московская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'170',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Созвездие", г. Воронеж','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Созвездие", г. Воронеж',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'171',@link_self,'Взнос в уставный капитал открытого акционерного общества "Усть-Среднеканская ГЭС", г. Магадан, Магаданская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Усть-Среднеканская ГЭС", г. Магадан, Магаданская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'173',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственный центр "Полюс", г. Томск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственный центр "Полюс", г. Томск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'174',@link_self,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Стрела", г. Оренбург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Стрела", г. Оренбург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'175',@link_self,'Взнос в уставный капитал открытого акционерного общества "Конструкторское бюро химавтоматики", г. Воронеж','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Конструкторское бюро химавтоматики", г. Воронеж',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'178',@link_self,'Взнос в уставный капитал открытого акционерного общества "Корпорация "Тактическое ракетное вооружение", г. Королев, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Корпорация "Тактическое ракетное вооружение", г. Королев, Московская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'180',@link_self,'Взнос в уставный капитал открытого акционерного общества "Объединенная авиастроительная корпорация", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Объединенная авиастроительная корпорация", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'181',@link_self,'Взнос в уставный капитал открытого акционерного общества Научно-производственное объединение "Сатурн", г. Рыбинск, Ярославская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества Научно-производственное объединение "Сатурн", г. Рыбинск, Ярославская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'184',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Авионика", г. Раменское, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Авионика", г. Раменское, Московская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'186',@link_self,'Взнос в уставный капитал открытого акционерного общества "Авиационная холдинговая компания "Сухой", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Авиационная холдинговая компания "Сухой", г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'188',@link_self,'Взнос в уставный капитал открытого акционерного общества "Красногорский завод имени С.А. Зверева", г. Красногорск, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Красногорский завод имени С.А. Зверева", г. Красногорск, Московская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'189',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Научно-производственное объединение "Электромашина", г. Челябинск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Научно-производственное объединение "Электромашина", г. Челябинск','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'198',@link_self,'Взнос в уставный капитал Ордена Почета открытого акционерного общества "Телемеханика", г. Нальчик, Кабардино-Балкарская Республика','ВР_2011',0,'',0,'','Взнос в уставный капитал Ордена Почета открытого акционерного общества "Телемеханика", г. Нальчик, Кабардино-Балкарская Республика','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'200',@link_self,'Закупка товаров, работ и услуг для государственных (муниципальных) нужд','ВР_2011',0,'',0,'','Закупка товаров, работ и услуг для государственных (муниципальных) нужд','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ и услуг  для государственных нужд', 'Закупка товаров, работ и услуг  для государственных нужд', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ и услуг для государственных (муниципальных) нужд', 'Закупка товаров, работ и услуг для государственных (муниципальных) нужд', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ и услуг для государственных нужд', 'Закупка товаров, работ и услуг для государственных нужд', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'201',@link_self,'Взнос в уставный капитал открытого акционерного общества "Тамбовский завод "Революционный труд", г. Тамбов','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Тамбовский завод "Революционный труд", г. Тамбов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'202',@link_self,'Взнос в уставный капитал открытого акционерного общества "Тамбовский научно-исследовательский институт радиотехники "ЭФИР", г. Тамбов','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Тамбовский научно-исследовательский институт радиотехники "ЭФИР", г. Тамбов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'203',@link_self,'Взнос в уставный капитал открытого акционерного общества "Тамбовский завод "Октябрь", г. Тамбов','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Тамбовский завод "Октябрь", г. Тамбов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'205',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Алмаз", г. Ростов-на-Дону','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Алмаз", г. Ростов-на-Дону','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'208',@link_self,'Взнос в уставный капитал открытого акционерного общества "Завод "Навигатор", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Завод "Навигатор", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '200' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'210',@link_self,'Разработка, закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Разработка, закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Разработка, закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа', 'Разработка, закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Разработка, закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества', 'Разработка, закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества', '20000101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'211',@link_self,'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','ВР_2011',0,'',0,'','Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения', 'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'212',@link_self,'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения','ВР_2011',0,'',0,'','Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения', 'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'213',@link_self,'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества вне рамок государственного оборонного заказа','ВР_2011',0,'',0,'','Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества вне рамок государственного оборонного заказа',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества вне рамок государственного оборонного заказа', 'Закупка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества вне рамок государственного оборонного заказа', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'214',@link_self,'Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','ВР_2011',0,'',0,'','Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения', 'Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'215',@link_self,'Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения','ВР_2011',0,'',0,'','Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения', 'Ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа вне рамок государственной программы вооружения', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'216',@link_self,'Фундаментальные исследования в интересах национальной обороны, национальной безопасности и правоохранительной деятельности в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','ВР_2011',0,'',0,'','Фундаментальные исследования в интересах национальной обороны, национальной безопасности и правоохранительной деятельности в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'217',@link_self,'Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','ВР_2011',0,'',0,'','Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исследования в области разработки вооружений, военной и  специальной техники, продукции производственно-технического  назначения и имущества в рамках государственного оборонного  заказа в целях обеспечения государственной программы вооружения', 'Исследования в области разработки вооружений, военной и  специальной техники, продукции производственно-технического  назначения и имущества в рамках государственного оборонного  заказа в целях обеспечения государственной программы вооружения', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения', 'Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа в целях обеспечения государственной программы вооружения', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'218',@link_self,'Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа вне рамок государственной программы вооружения','ВР_2011',0,'',0,'','Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа вне рамок государственной программы вооружения','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исследования в области разработки вооружений, военной и  специальной техники, продукции производственно-технического  назначения и имущества в рамках государственного оборонного  заказа вне рамок государственной программы вооружения', 'Исследования в области разработки вооружений, военной и  специальной техники, продукции производственно-технического  назначения и имущества в рамках государственного оборонного  заказа вне рамок государственной программы вооружения', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа вне рамок государственной программы вооружения', 'Исследования в области разработки вооружений, военной и специальной техники, продукции производственно-технического назначения в рамках государственного оборонного заказа вне рамок государственной программы вооружения', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '210' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'219',@link_self,'Закупка работ и услуг в целях обеспечения мероприятий в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Закупка работ и услуг в целях обеспечения мероприятий в рамках государственного оборонного заказа',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка работ и услуг в целях обеспечения мероприятий в рамках государственного оборонного заказа', 'Закупка работ и услуг в целях обеспечения мероприятий в рамках государственного оборонного заказа', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '200' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'220',@link_self,'Закупка товаров, работ и услуг для обеспечения специальным топливом и горюче-смазочными материалами, продовольственного и вещевого обеспечения органов в сфере национальной безопасности, правоохранительной деятельности и обороны','ВР_2011',0,'',0,'','Закупка товаров, работ и услуг для обеспечения специальным топливом и горюче-смазочными материалами, продовольственного и вещевого обеспечения органов в сфере национальной безопасности, правоохранительной деятельности и обороны',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ и услуг для обеспечения специальным  топливом и горюче-смазочными материалами, продовольственного и вещевого обеспечения органов в сфере национальной безопасности, правоохранительной деятельности и обороны', 'Закупка товаров, работ и услуг для обеспечения специальным  топливом и горюче-смазочными материалами, продовольственного и вещевого обеспечения органов в сфере национальной безопасности, правоохранительной деятельности и обороны', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ и услуг для обеспечения специальным топливом и горюче-смазочными материалами, продовольственного и вещевого обеспечения органов в сфере национальной безопасности, правоохранительной деятельности и обороны', 'Закупка товаров, работ и услуг для обеспечения специальным топливом и горюче-смазочными материалами, продовольственного и вещевого обеспечения органов в сфере национальной безопасности, правоохранительной деятельности и обороны', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '220' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'221',@link_self,'Обеспечение специальным топливом и горюче-смазочными материалами в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Обеспечение специальным топливом и горюче-смазочными материалами в рамках государственного оборонного заказа','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '220' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'222',@link_self,'Обеспечение специальным топливом и горюче-смазочными материалами вне рамок государственного оборонного заказа','ВР_2011',0,'',0,'','Обеспечение специальным топливом и горюче-смазочными материалами вне рамок государственного оборонного заказа','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '220' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'223',@link_self,'Продовольственное обеспечение в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Продовольственное обеспечение в рамках государственного оборонного заказа',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Продовольственное обеспечение в рамках  государственного оборонного заказа', 'Продовольственное обеспечение в рамках  государственного оборонного заказа', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Продовольственное обеспечение в рамках государственного оборонного заказа', 'Продовольственное обеспечение в рамках государственного оборонного заказа', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '220' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'224',@link_self,'Продовольственное обеспечение вне рамок государственного оборонного заказа','ВР_2011',0,'',0,'','Продовольственное обеспечение вне рамок государственного оборонного заказа',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Продовольственное обеспечение вне рамок государственного оборонного заказа', 'Продовольственное обеспечение вне рамок государственного оборонного заказа', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '220' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'225',@link_self,'Вещевое обеспечение в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Вещевое обеспечение в рамках государственного оборонного заказа','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Вещевое обеспечение в рамках государственного оборонного заказа', 'Вещевое обеспечение в рамках государственного оборонного заказа', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '220' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'226',@link_self,'Вещевое обеспечение вне рамок государственного оборонного заказа','ВР_2011',0,'',0,'','Вещевое обеспечение вне рамок государственного оборонного заказа','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '200' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'230',@link_self,'Закупка товаров, работ, услуг в целях формирования государственного материального резерва','ВР_2011',0,'',0,'','Закупка товаров, работ, услуг в целях формирования государственного материального резерва','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'232',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Старт", г. Великий Новгород','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Старт", г. Великий Новгород','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'234',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский технологический институт "Техномаш", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский технологический институт "Техномаш", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'235',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Гранит-Электрон", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Гранит-Электрон", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'237',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт "Курс", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт "Курс", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'238',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Моринформсистема-Агат", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Моринформсистема-Агат", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'239',@link_self,'Взнос в уставный капитал открытого акционерного общества "Таганрогский завод "Прибой", г. Таганрог, Ростовская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Таганрогский завод "Прибой", г. Таганрог, Ростовская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '200' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'240',@link_self,'Иные закупки товаров, работ и услуг для обеспечения государственных (муниципальных) нужд','ВР_2011',0,'',0,'','Иные закупки товаров, работ и услуг для обеспечения государственных (муниципальных) нужд','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные закупки товаров, работ и услуг для государственных нужд', 'Иные закупки товаров, работ и услуг для государственных нужд', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Иные закупки товаров, работ и услуг для обеспечения государственных (муниципальных) нужд', 'Иные закупки товаров, работ и услуг для обеспечения государственных (муниципальных) нужд', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '240' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'241',@link_self,'Научно-исследовательские и опытно-конструкторские работы','ВР_2011',0,'',0,'','Научно-исследовательские и опытно-конструкторские работы','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '240' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'242',@link_self,'Закупка товаров, работ, услуг в сфере информационно-коммуникационных технологий','ВР_2011',0,'',0,'','Закупка товаров, работ, услуг в сфере информационно-коммуникационных технологий','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '240' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'243',@link_self,'Закупка товаров, работ, услуг в целях капитального ремонта государственного (муниципального) имущества','ВР_2011',0,'',0,'','Закупка товаров, работ, услуг в целях капитального ремонта государственного (муниципального) имущества','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ, услуг в целях капитального ремонта государственного (муниципального) имущества', 'Закупка товаров, работ, услуг в целях капитального ремонта государственного (муниципального) имущества', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Закупка товаров, работ, услуг в целях капитального ремонта государственного имущества', 'Закупка товаров, работ, услуг в целях капитального ремонта государственного имущества', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '240' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'244',@link_self,'Прочая закупка товаров, работ и услуг для обеспечения государственных (муниципальных) нужд','ВР_2011',0,'',0,'','Прочая закупка товаров, работ и услуг для обеспечения государственных (муниципальных) нужд','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Прочая закупка товаров, работ и услуг для государственных нужд', 'Прочая закупка товаров, работ и услуг для государственных нужд', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Прочая закупка товаров, работ и услуг для обеспечения государственных (муниципальных) нужд', 'Прочая закупка товаров, работ и услуг для обеспечения государственных (муниципальных) нужд', '20140206'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'246',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-технологическая компания "Ригель", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-технологическая компания "Ригель", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'254',@link_self,'Взнос в уставный капитал открытого акционерного общества "Объединенная промышленная корпорация "Оборонпром", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Объединенная промышленная корпорация "Оборонпром", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'256',@link_self,'Взнос в уставный капитал открытого акционерного общества "Светлана", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Светлана", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'257',@link_self,'Взнос в уставный капитал открытого акционерного общества "Авангард", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Авангард", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'262',@link_self,'Взнос в уставный капитал открытого акционерного общества "Российская электроника", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Российская электроника", г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'269',@link_self,'Поддержание объектов наземной инфраструктуры системы ГЛОНАСС, информационно-техническое обеспечение мероприятий по реализации федеральной целевой программы','ВР_2011',0,'',0,'','Поддержание объектов наземной инфраструктуры системы ГЛОНАСС, информационно-техническое обеспечение мероприятий по реализации федеральной целевой программы',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'270',@link_self,'Органы управления государственных внебюджетных фондов','ВР_2011',0,'',0,'','Органы управления государственных внебюджетных фондов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'278',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Квант", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Квант", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'291',@link_self,'Взнос в уставный капитал открытого акционерного общества "Пермский завод "Машиностроитель", г. Пермь','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Пермский завод "Машиностроитель", г. Пермь','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'296',@link_self,'Взнос в уставный капитал открытого акционерного общества "Институт пластмасс имени Г.С. Петрова", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Институт пластмасс имени Г.С. Петрова", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'300',@link_self,'Социальное обеспечение и иные выплаты населению','ВР_2011',0,'',0,'','Социальное обеспечение и иные выплаты населению',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Социальное обеспечение и иные выплаты населению', 'Социальное обеспечение и иные выплаты населению', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'302',@link_self,'Мероприятия, связанные с развитием инфраструктуры космодрома "Плесецк" космодромов на 2006 - 2015 годы".','ВР_2011',0,'',0,'','Мероприятия, связанные с развитием инфраструктуры космодрома "Плесецк" космодромов на 2006 - 2015 годы".',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'304',@link_self,'Взнос в уставный капитал открытого акционерного общества "Камчатский газоэнергетический комплекс" (г. Петропавловск-Камчатский, Камчатский край)','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Камчатский газоэнергетический комплекс" (г. Петропавловск-Камчатский, Камчатский край)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'305',@link_self,'Взнос в уставный капитал Советско-Монгольского акционерного общества "Улан-Баторская железная дорога"
','ВР_2011',0,'',0,'','Взнос в уставный капитал Советско-Монгольского акционерного общества "Улан-Баторская железная дорога"
',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'309',@link_self,'Взнос в уставный капитал открытого акционерного общества "Федеральная сетевая компания Единой энергетической системы" (г. Москва)','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Федеральная сетевая компания Единой энергетической системы" (г. Москва)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '300' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'310',@link_self,'Публичные нормативные социальные  выплаты гражданам','ВР_2011',0,'',0,'','Публичные нормативные социальные  выплаты гражданам','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '310' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'311',@link_self,'Пенсии, выплачиваемые по пенсионному страхованию населения','ВР_2011',0,'',0,'','Пенсии, выплачиваемые по пенсионному страхованию населения','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '310' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'312',@link_self,'Иные пенсии, социальные доплаты к пенсиям','ВР_2011',0,'',0,'','Иные пенсии, социальные доплаты к пенсиям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные пенсии, социальные доплаты к пенсиям', 'Иные пенсии, социальные доплаты к пенсиям', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Пенсии, выплачиваемые организациями сектора государственного управления', 'Пенсии, выплачиваемые организациями сектора государственного управления', '20000101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '310' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'313',@link_self,'Пособия, компенсации, меры социальной поддержки по публичным нормативным обязательствам','ВР_2011',0,'',0,'','Пособия, компенсации, меры социальной поддержки по публичным нормативным обязательствам','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Пособия и компенсации по публичным нормативным обязательствам', 'Пособия и компенсации по публичным нормативным обязательствам', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Пособия, компенсации, меры социальной поддержки по публичным нормативным обязательствам', 'Пособия, компенсации, меры социальной поддержки по публичным нормативным обязательствам', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '310' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'314',@link_self,'Меры социальной поддержки населения по публичным нормативным обязательствам','ВР_2011',0,'',0,'','Меры социальной поддержки населения по публичным нормативным обязательствам','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '310' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'317',@link_self,'Федеральный научно-клинический центр детской гематологии, онкологии и иммунологии, г. Москва','ВР_2011',0,'',0,'','Федеральный научно-клинический центр детской гематологии, онкологии и иммунологии, г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '300' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'320',@link_self,'Социальные выплаты гражданам, кроме публичных нормативных социальных выплат','ВР_2011',0,'',0,'','Социальные выплаты гражданам, кроме публичных нормативных социальных выплат','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '320' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'321',@link_self,'Пособия, компенсации и иные социальные выплаты гражданам, кроме публичных нормативных обязательств','ВР_2011',0,'',0,'','Пособия, компенсации и иные социальные выплаты гражданам, кроме публичных нормативных обязательств','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Пособия и компенсации гражданам и иные социальные выплаты, кроме публичных нормативных обязательств', 'Пособия и компенсации гражданам и иные социальные выплаты, кроме публичных нормативных обязательств', '20000101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Пособия, компенсации и иные социальные выплаты гражданам, кроме публичных нормативных обязательств', 'Пособия, компенсации и иные социальные выплаты гражданам, кроме публичных нормативных обязательств', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '320' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'322',@link_self,'Субсидии гражданам на приобретение жилья','ВР_2011',0,'',0,'','Субсидии гражданам на приобретение жилья','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '320' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'323',@link_self,'Приобретение товаров, работ, услуг в пользу граждан в целях их социального обеспечения','ВР_2011',0,'',0,'','Приобретение товаров, работ, услуг в пользу граждан в целях их социального обеспечения','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Приобретение товаров, работ, услуг в пользу граждан в целях их социального обеспечения', 'Приобретение товаров, работ, услуг в пользу граждан в целях их социального обеспечения', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Приобретение товаров, работ, услуг в пользу граждан', 'Приобретение товаров, работ, услуг в пользу граждан', '20000101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'326',@link_self,'Стр-во в СПб Орловского тоннеля под р.Невой','ВР_2011',0,'',0,'','Строительство в г. Санкт-Петербурге Орловского тоннеля под р. Невой в рамках развития Волго-Балтийского водного пути',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'327',@link_self,'Стр-во нового выхода на МКАД с М-1 "Беларусь"','ВР_2011',0,'',0,'','Строительство нового выхода на Московскую кольцевую автомобильную дорогу с федеральной автомобильной дороги М-1 "Беларусь" Москва - Минск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'328',@link_self,'Стр-во скор.а/д Москва-СПб на участке 15-58 км','ВР_2011',0,'',0,'','Строительство скоростной автомобильной дороги Москва - Санкт-Петербург на участке 15-й км - 58-й км',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'329',@link_self,'Комплексное развитие Нижнего Приангарья','ВР_2011',0,'',0,'','Комплексное развитие Нижнего Приангарья',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '300' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'330',@link_self,'Публичные нормативные выплаты гражданам несоциального характера','ВР_2011',0,'',0,'','Публичные нормативные выплаты гражданам несоциального характера',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Публичные нормативные выплаты гражданам несоциального характера', 'Публичные нормативные выплаты гражданам несоциального характера', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'331',@link_self,'Комплекс нефтепер.и нефтехим.заводов в Нижнекамске','ВР_2011',0,'',0,'','Комплекс нефтеперерабатывающих и нефтехимических заводов в г. Нижнекамске',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'332',@link_self,'Стр-во ж/д станции Кызыл-Курагино (осв.МСБ Р.Тыва)','ВР_2011',0,'',0,'','Строительство железнодорожной станции Кызыл-Курагино в увязке с освоением минерально-сырьевой базы Республики Тыва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'335',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственный центр "Ригель", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственный центр "Ригель", г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'336',@link_self,'Разр.пр.док.на стр-во скор.а/д Москва-СПб 58-684км','ВР_2011',0,'',0,'','Разработка проектной документации на строительство скоростной автомобильной дороги Москва - Санкт-Петербург на участке км 58 - км 684 (с последующей эксплуатацией на платной основе)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'338',@link_self,'Разр.пр.док.для инв.проекта "Компл.разв.Юж.Якутии"','ВР_2011',0,'',0,'','Разработка проектной документации для реализации инвестиционного проекта "Комплексное развитие Южной Якутии"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'339',@link_self,'Компл.прогр.стр-ва объектов водосн.Ростова-на-Дону','ВР_2011',0,'',0,'','Комплексная программа строительства и реконструкции объектов водоснабжения и водоотведения г. Ростова-на-Дону и юго-запада Ростовской области',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '300' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'340',@link_self,'Стипендии','ВР_2011',0,'',0,'','Стипендии',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Стипендии', 'Стипендии', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'343',@link_self,'Мероприятия по развитию методической составляющей системы обеспечения единства измерений в наноиндустрии и безопасности создания и применения объектов наноиндустрии','ВР_2011',0,'',0,'','Мероприятия по развитию методической составляющей системы обеспечения единства измерений в наноиндустрии и безопасности создания и применения объектов наноиндустрии',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'344',@link_self,'Взнос в уставный капитал открытого акционерного общества "Рыбинский завод приборостроения", г. Рыбинск, Ярославская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Рыбинский завод приборостроения", г. Рыбинск, Ярославская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'345',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Рубин", г. Пенза','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Рубин", г. Пенза',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'346',@link_self,'Взнос в уставный капитал открытого акционерного общества "Инженерно-маркетинговый центр Концерна "Вега", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Инженерно-маркетинговый центр Концерна "Вега", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'347',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Правдинский радиозавод", г. Балахна, Нижегородская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Правдинский радиозавод", г. Балахна, Нижегородская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'349',@link_self,'Взнос в уставный капитал открытого акционерного общества "Воронежский научно-исследовательский институт "Вега", г. Воронеж','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Воронежский научно-исследовательский институт "Вега", г. Воронеж',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '300' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'350',@link_self,'Премии и гранты','ВР_2011',0,'',0,'','Премии и гранты','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'353',@link_self,'Взнос в уставный капитал открытого акционерного общества "Институт электронных управляющих машин им. И.С. Брука", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Институт электронных управляющих машин им. И.С. Брука", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'357',@link_self,'Взнос в уставный капитал открытого акционерного общества "Информационные спутниковые системы" имени академика М.Ф. Решетнёва", г. Железногорск, Красноярский край','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Информационные спутниковые системы" имени академика М.Ф. Решетнёва", г. Железногорск, Красноярский край',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'358',@link_self,'Взнос в уставный капитал открытого акционерного общества "Сибирские приборы и системы", г. Омск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Сибирские приборы и системы", г. Омск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'359',@link_self,'Взнос в уставный капитал открытого акционерного общества "Российские железные дороги"','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Российские железные дороги"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '300' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'360',@link_self,'Иные выплаты населению','ВР_2011',0,'',0,'','Иные выплаты населению','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'361',@link_self,'Разр.пр.док.для инв.проекта "Стр-во ЦКАД Моск.об."','ВР_2011',0,'',0,'','Разработка проектной документации для реализации инвестиционного проекта "Строительство Центральной кольцевой автомобильной дороги Московской области"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'362',@link_self,'Взнос в уставный капитал Черноморского банка торговли и развития','ВР_2011',0,'',0,'','Взнос в уставный капитал Черноморского банка торговли и развития',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'363',@link_self,'Взнос в уставный капитал открытого акционерного общества "Дальневосточная энергетическая управляющая компания", г. Владивосток','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Дальневосточная энергетическая управляющая компания", г. Владивосток',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'365',@link_self,'Взнос в уставный капитал открытого акционерного общества "Пермская научно-производственная приборостроительная компания", г. Пермь','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Пермская научно-производственная приборостроительная компания", г. Пермь',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'367',@link_self,'Взнос в уставный капитал открытого акционерного общества "Равенство", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Равенство", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'368',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт полупроводниковых приборов", г. Томск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт полупроводниковых приборов", г. Томск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'369',@link_self,'Взнос в уставный капитал открытого акционерного общества "Агрегатное конструкторское бюро "Якорь", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Агрегатное конструкторское бюро "Якорь", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'370',@link_self,'Взнос в уставный капитал открытого акционерного общества "Полигон", г. Томск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Полигон", г. Томск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'372',@link_self,'Стр-во и посл.экспл. МПК "Юг-2" в порту Усть-Луга','ВР_2011',0,'',0,'','Строительство и последующая эксплуатация многопрофильного перегрузочного комплекса "Юг-2" в морском торговом порту Усть-Луга',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'373',@link_self,'Вторая очередь программы развития агропромышленного комплекса Тамбовской области','ВР_2011',0,'',0,'','Вторая очередь программы развития агропромышленного комплекса Тамбовской области','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'374',@link_self,'Создание регионального индустриального парка в городе Невинномысске Ставропольского края','ВР_2011',0,'',0,'','Создание регионального индустриального парка в городе Невинномысске Ставропольского края','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'375',@link_self,'Создание завода по производству полиэтилентерефталата (ПЭТФ) пищевого и текстильного назначения производственной мощностью 486 тыс. тонн в год','ВР_2011',0,'',0,'','Создание завода по производству полиэтилентерефталата (ПЭТФ) пищевого и текстильного назначения производственной мощностью 486 тыс. тонн в год','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'376',@link_self,'Взнос в уставный капитал открытого акционерного общества "КазХимНИИ", г. Казань','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "КазХимНИИ", г. Казань',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'377',@link_self,'Строительство и эксплуатация на платной основе мостовых переходов  через реку Кама и реку Буй у города Камбарка на автомобильной дороге  Ижевск - Сарапул - Камбарка - граница Республики Башкортостан в Удмуртской Республике','ВР_2011',0,'',0,'','Строительство и эксплуатация на платной основе мостовых переходов  через реку Кама и реку Буй у города Камбарка на автомобильной дороге  Ижевск - Сарапул - Камбарка - граница Республики Башкортостан в Удмуртской Республике','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'378',@link_self,'Взнос в уставный капитал открытого акционерного общества "Электростальское научно-производственное объединение "Неорганика", г. Электросталь, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Электростальское научно-производственное объединение "Неорганика", г. Электросталь, Московская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'379',@link_self,'Взнос в уставный капитал открытого акционерного общества "Корпорация "Росхимзащита", г. Тамбов','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Корпорация "Росхимзащита", г. Тамбов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'383',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Государственный ракетный центр имени академика В.П.Макеева", г. Миасс','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Государственный ракетный центр имени академика В.П.Макеева", г. Миасс','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'386',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Геофизика-Космос", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Геофизика-Космос", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'387',@link_self,'Поддержка программ развития инновационной инфраструктуры, включая поддержку малого инновационного предпринимательства, в федеральных образовательных учреждениях высшего профессионального образования','ВР_2011',0,'',0,'','Поддержка программ развития инновационной инфраструктуры, включая поддержку малого инновационного предпринимательства, в федеральных образовательных учреждениях высшего профессионального образования',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'388',@link_self,'Развитие сети национальных университетов и других образовательных учреждений','ВР_2011',0,'',0,'','Развитие сети национальных университетов и других образовательных учреждений',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'390',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственная корпорация "Уралвагонзавод" имени Ф.Э. Дзержинского", г. Нижний Тагил, Свердловская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственная корпорация "Уралвагонзавод" имени Ф.Э. Дзержинского", г. Нижний Тагил, Свердловская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'391',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Центральный научно-исследовательский институт "Буревестник", г. Нижний Новгород','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Центральный научно-исследовательский институт "Буревестник", г. Нижний Новгород','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'392',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Государственный научно-исследовательский институт машиностроения  имени В.В. Бахирева", г. Дзержинск, Нижегородская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Государственный научно-исследовательский институт машиностроения  имени В.В. Бахирева", г. Дзержинск, Нижегородская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'393',@link_self,'Взнос в уставный капитал открытого акционерного общества "Северный Рейд", г. Северодвинск, Архангельская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Северный Рейд", г. Северодвинск, Архангельская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'394',@link_self,'Взнос в уставный капитал открытого акционерного общества "Северное производственное объединение "АРКТИКА", г. Северодвинск, Архангельская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Северное производственное объединение "АРКТИКА", г. Северодвинск, Архангельская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'396',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт морской теплотехники", г. Ломоносов,  г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт морской теплотехники", г. Ломоносов,  г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'397',@link_self,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Северное машиностроительное предприятие", г. Северодвинск, Архангельская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Северное машиностроительное предприятие", г. Северодвинск, Архангельская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'400',@link_self,'Капитальные вложения в объекты недвижимого имущества государственной (муниципальной) собственности','ВР_2011',0,'',0,'','Капитальные вложения в объекты недвижимого имущества государственной (муниципальной) собственности','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции', 'Бюджетные инвестиции', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Капитальные вложения в объекты недвижимого имущества государственной (муниципальной) собственности', 'Капитальные вложения в объекты недвижимого имущества государственной (муниципальной) собственности', '20140206'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'401',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн ПВО "Алмаз-Антей", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн ПВО "Алмаз-Антей", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'402',@link_self,'Взнос в уставный капитал открытого акционерного общества "Сибирский химический комбинат", г. Северск, Томская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Сибирский химический комбинат", г. Северск, Томская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'403',@link_self,'Взнос в уставный капитал открытого акционерного общества "Государственный научный центр - Научно-исследовательский институт атомных реакторов", г. Димитровград-10, Ульяновская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Государственный научный центр - Научно-исследовательский институт атомных реакторов", г. Димитровград-10, Ульяновская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'404',@link_self,'Взнос в уставный капитал открытого акционерного общества "Опытное Конструкторское Бюро Машиностроения имени И.И. Африкантова, г. Нижний Новгород','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Опытное Конструкторское Бюро Машиностроения имени И.И. Африкантова, г. Нижний Новгород',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'407',@link_self,'Взнос в уставный капитал открытого акционерного общества "Ступинская металлургическая компания", г. Ступино, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Ступинская металлургическая компания", г. Ступино, Московская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'409',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт химикатов для полимерных материалов", г. Тамбов','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт химикатов для полимерных материалов", г. Тамбов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '400' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'410',@link_self,'Бюджетные инвестиции','ВР_2011',0,'',0,'','Бюджетные инвестиции','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности федеральным государственным учреждениям', 'Бюджетные инвестиции в объекты государственной собственности федеральным государственным учреждениям', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции', 'Бюджетные инвестиции', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'411',@link_self,'Бюджетные инвестиции в объекты государственной собственности казенным учреждениям вне рамок государственного оборонного заказа','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты государственной собственности казенным учреждениям вне рамок государственного оборонного заказа',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности казенным учреждениям вне рамок государственного оборонного заказа', 'Бюджетные инвестиции в объекты государственной собственности казенным учреждениям вне рамок государственного оборонного заказа', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'412',@link_self,'Бюджетные инвестиции на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность','ВР_2011',0,'',0,'','Бюджетные инвестиции на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты  государственной собственности казенным учреждениям  в рамках государственного оборонного заказа', 'Бюджетные инвестиции в объекты  государственной собственности казенным учреждениям  в рамках государственного оборонного заказа', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности казенным учреждениям в рамках государственного оборонного заказа', 'Бюджетные инвестиции в объекты государственной собственности казенным учреждениям в рамках государственного оборонного заказа', '20130101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность', 'Бюджетные инвестиции на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'413',@link_self,'Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности бюджетным учреждениям вне рамок государственного оборонного заказа', 'Бюджетные инвестиции в объекты государственной собственности бюджетным учреждениям вне рамок государственного оборонного заказа', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа', 'Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'414',@link_self,'Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности бюджетным учреждениям в рамках государственного оборонного заказа', 'Бюджетные инвестиции в объекты государственной собственности бюджетным учреждениям в рамках государственного оборонного заказа', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа', 'Бюджетные инвестиции в объекты капитального строительства в рамках государственного оборонного заказа', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'415',@link_self,'Бюджетные инвестиции в соответствии с концессионными соглашениями','ВР_2011',0,'',0,'','Бюджетные инвестиции в соответствии с концессионными соглашениями','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности автономным учреждениям', 'Бюджетные инвестиции в объекты государственной собственности автономным учреждениям', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в соответствии с концессионными соглашениями', 'Бюджетные инвестиции в соответствии с концессионными соглашениями', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'418',@link_self,'Взнос в уставный капитал открытого акционерного общества "Атомспецтранс", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Атомспецтранс", г. Москва','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '400' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'420',@link_self,'Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '420' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'421',@link_self,'Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям, основанным на праве оперативного управления','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям, основанным на праве оперативного управления',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям, основанным на праве оперативного управления', 'Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям, основанным на праве оперативного управления', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '420' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'422',@link_self,'Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям, основанным на праве хозяйственного ведения','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты государственной собственности государственным унитарным предприятиям, основанным на праве хозяйственного ведения','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'424',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт технической физики и автоматизации", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт технической физики и автоматизации", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'425',@link_self,'Взнос в уставный капитал открытого акционерного общества "Высокотехнологический научно-исследовательский институт неорганических материалов имени академика А.А. Бочвара", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Высокотехнологический научно-исследовательский институт неорганических материалов имени академика А.А. Бочвара", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'427',@link_self,'Взнос в уставный капитал открытого акционерного общества "Московская специализированная типография № 27", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Московская специализированная типография № 27", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'429',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Морское подводное оружие - Гидроприбор", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Морское подводное оружие - Гидроприбор", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '400' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'430',@link_self,'Бюджетные инвестиции в объекты государственных внебюджетных фондов','ВР_2011',0,'',0,'','Бюджетные инвестиции в объекты государственных внебюджетных фондов',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции в объекты государственных внебюджетных фондов', 'Бюджетные инвестиции в объекты государственных внебюджетных фондов', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'431',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центр технологии судостроения и судоремонта", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центр технологии судостроения и судоремонта", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'433',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центр судоремонта "Звездочка", г. Северодвинск, Архангельская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центр судоремонта "Звездочка", г. Северодвинск, Архангельская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'434',@link_self,'Взнос в уставный капитал открытого акционерного общества "Дальневосточный завод "Звезда", г. Большой Камень, Приморский край','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Дальневосточный завод "Звезда", г. Большой Камень, Приморский край',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'435',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт двигателей", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт двигателей", г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'437',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Центральный научно-исследовательский институт "Электроприбор", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Центральный научно-исследовательский институт "Электроприбор", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'438',@link_self,'Взнос в уставный капитал открытого акционерного общества "Концерн "Научно-производственное объединение "Аврора", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Концерн "Научно-производственное объединение "Аврора", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'439',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Центральное морское конструкторское бюро "Алмаз", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Центральное морское конструкторское бюро "Алмаз", г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '400' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'440',@link_self,'Бюджетные инвестиции на приобретение объектов недвижимого имущества','ВР_2011',0,'',0,'','Бюджетные инвестиции на приобретение объектов недвижимого имущества','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции на приобретение объектов недвижимого имущества', 'Бюджетные инвестиции на приобретение объектов недвижимого имущества', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '440' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'441',@link_self,'Бюджетные инвестиции на приобретение объектов недвижимого имущества казенным учреждениям','ВР_2011',0,'',0,'','Бюджетные инвестиции на приобретение объектов недвижимого имущества казенным учреждениям','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции на приобретение объектов недвижимого имущества казенным учреждениям', 'Бюджетные инвестиции на приобретение объектов недвижимого имущества казенным учреждениям', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '440' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'442',@link_self,'Бюджетные инвестиции на приобретение объектов недвижимого имущества бюджетным учреждениям','ВР_2011',0,'',0,'','Бюджетные инвестиции на приобретение объектов недвижимого имущества бюджетным учреждениям',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Бюджетные инвестиции на приобретение объектов недвижимого имущества бюджетным учреждениям', 'Бюджетные инвестиции на приобретение объектов недвижимого имущества бюджетным учреждениям', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '440' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'443',@link_self,'Бюджетные инвестиции на приобретение объектов недвижимого имущества автономным учреждениям','ВР_2011',0,'',0,'','Бюджетные инвестиции на приобретение объектов недвижимого имущества автономным учреждениям','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'444',@link_self,'Реализация государственных полномочий по проведению государственной экологической экспертизы','ВР_2011',0,'',0,'','Реализация государственных полномочий по проведению государственной экологической экспертизы',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '440' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'446',@link_self,'Бюджетные инвестиции на приобретение объектов недвижимого имущества государственным внебюджетным фондам','ВР_2011',0,'',0,'','Бюджетные инвестиции на приобретение объектов недвижимого имущества государственным внебюджетным фондам','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '400' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'450',@link_self,'Бюджетные инвестиции иным юридическим лицам','ВР_2011',0,'',0,'','Бюджетные инвестиции иным юридическим лицам','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'453',@link_self,'Взнос в уставный капитал открытого акционерного общества Красноярский машиностроительный завод", г. Красноярск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества Красноярский машиностроительный завод", г. Красноярск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'454',@link_self,'Первая очередь программы развития АПК Тамб.обл.','ВР_2011',0,'',0,'','Первая очередь программы развития АПК Тамбовской области',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'457',@link_self,'Взнос в уставный капитал открытого акционерного общества "Государственный научно-исследовательский и проектный институт редкометаллической промышленности "Гиредмет", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Государственный научно-исследовательский и проектный институт редкометаллической промышленности "Гиредмет", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'458',@link_self,'Взнос в уставный капитал открытого акционерного общества "Опытный завод тугоплавких металлов и твердых сплавов", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Опытный завод тугоплавких металлов и твердых сплавов", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'459',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственная корпорация "Системы прецизионного приборостроения", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственная корпорация "Системы прецизионного приборостроения", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'460',@link_self,'Субсидии на осуществление капитальных вложений бюджетным и автономным учреждениям, государственным унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений бюджетным и автономным учреждениям, государственным унитарным предприятиям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'460',@link_self,'Субсидии на осуществление капитальных вложений бюджетным и автономным учреждениям, государственным унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений бюджетным и автономным учреждениям, государственным унитарным предприятиям',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт физических измерений", г. Пенза', 'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт физических измерений", г. Пенза', '20000101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'461',@link_self,'Взнос в уставный капитал открытого акционерного общества "Уральский научно-исследовательский институт композиционных материалов", г. Пермь','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Уральский научно-исследовательский институт композиционных материалов", г. Пермь',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'461',@link_self,'Субсидии на приобретение объектов недвижимости бюджетным учреждениям','ВР_2011',0,'',0,'','Субсидии на приобретение объектов недвижимости бюджетным учреждениям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на приобретение объектов недвижимости бюджетным учреждениям', 'Субсидии на приобретение объектов недвижимости бюджетным учреждениям', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'462',@link_self,'Взнос в уставный капитал открытого акционерного общества "Зеленодольское проектно-конструкторское бюро", г. Зеленодольск, Республика Татарстан','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Зеленодольское проектно-конструкторское бюро", г. Зеленодольск, Республика Татарстан',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'462',@link_self,'Субсидии на приобретение объектов недвижимости автономным учреждениям','ВР_2011',0,'',0,'','Субсидии на приобретение объектов недвижимости автономным учреждениям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на приобретение объектов недвижимости автономным учреждениям', 'Субсидии на приобретение объектов недвижимости автономным учреждениям', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'463',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательское проектно-технологическое бюро "Онега", г. Северодвинск, Архангельская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательское проектно-технологическое бюро "Онега", г. Северодвинск, Архангельская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'463',@link_self,'Субсидии на приобретение объектов недвижимости государственным унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на приобретение объектов недвижимости государственным унитарным предприятиям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на приобретение объектов недвижимости государственным унитарным предприятиям', 'Субсидии на приобретение объектов недвижимости государственным унитарным предприятиям', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'464',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро морской техники "Рубин", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро морской техники "Рубин", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'464',@link_self,'Субсидии на осуществление капитальных вложений в объекты капитального строительства бюджетным учреждениям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений в объекты капитального строительства бюджетным учреждениям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на осуществление капитальных вложений в объекты капитального строительства бюджетным учреждениям', 'Субсидии на осуществление капитальных вложений в объекты капитального строительства бюджетным учреждениям', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'465',@link_self,'Взнос в уставный капитал открытого акционерного общества "Ново-Вятка", г. Киров','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Ново-Вятка", г. Киров','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'465',@link_self,'Субсидии на осуществление капитальных вложений в объекты капитального строительства автономным учреждениям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений в объекты капитального строительства автономным учреждениям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на осуществление капитальных вложений в объекты капитального строительства автономным учреждениям', 'Субсидии на осуществление капитальных вложений в объекты капитального строительства автономным учреждениям', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'466',@link_self,'Взнос в уставный капитал открытого акционерного общества "Уральский завод транспортного машиностроения", г. Екатеринбург,  Свердловская область";','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Уральский завод транспортного машиностроения", г. Екатеринбург,  Свердловская область";','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'466',@link_self,'Субсидии на осуществление капитальных вложений в объекты капитального строительства государственным унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений в объекты капитального строительства государственным унитарным предприятиям','20130101','20131231'
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на осуществление капитальных вложений в объекты капитального строительства государственным унитарным предприятиям', 'Субсидии на осуществление капитальных вложений в объекты капитального строительства государственным унитарным предприятиям', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'471',@link_self,'Стр-во комб-та по глуб.перераб.древ."Зел.фабрика"','ВР_2011',0,'',0,'','Строительство комбината по глубокой переработке древесины "Зеленая фабрика"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'473',@link_self,'Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Холдинг межрегиональных распределительных сетевых компаний"','ВР_2011',0,'',0,'','Приобретение дополнительных акций, выпускаемых при увеличении уставного капитала открытого акционерного общества "Холдинг межрегиональных распределительных сетевых компаний"',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'474',@link_self,'Металлургический завод СтавСталь. 1-ая очередь. Комплекс прокатного цеха','ВР_2011',0,'',0,'','Металлургический завод СтавСталь. 1-ая очередь. Комплекс прокатного цеха','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'475',@link_self,'Развитие инфраструктуры завода по розливу минеральной воды в  с. Средние Ачалуки Малгобекского района Республики Ингушетия','ВР_2011',0,'',0,'','Развитие инфраструктуры завода по розливу минеральной воды в  с. Средние Ачалуки Малгобекского района Республики Ингушетия','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'476',@link_self,'Строительство завода по производству гипса и гипсосодержащих строительных материалов в промышленной зоне с. Кафыр-Кумух  Республики Дагестан','ВР_2011',0,'',0,'','Строительство завода по производству гипса и гипсосодержащих строительных материалов в промышленной зоне с. Кафыр-Кумух  Республики Дагестан','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'477',@link_self,'Строительство инфраструктуры кластера по добыче стекольного сырья для производства стеклянной тары в Республике Ингушетия','ВР_2011',0,'',0,'','Строительство инфраструктуры кластера по добыче стекольного сырья для производства стеклянной тары в Республике Ингушетия','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'478',@link_self,'Создание комплекса по переработке газа Северного Каспия  в этилен, полиэтилен и полипропилен (I очередь)','ВР_2011',0,'',0,'','Создание комплекса по переработке газа Северного Каспия  в этилен, полиэтилен и полипропилен (I очередь)','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'479',@link_self,'Завод по производству  готовых лекарственных форм антибиотиков','ВР_2011',0,'',0,'','Завод по производству  готовых лекарственных форм антибиотиков','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'480',@link_self,'Стр-во объектов инфр-ры г.Уфы Р.Башкортостан','ВР_2011',0,'',0,'','Строительство объектов социальной и инженерной инфраструктуры города Уфы Республики Башкортостан',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'481',@link_self,'Чистый Дон','ВР_2011',0,'',0,'','Чистый Дон',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'482',@link_self,'Стр-во инж.сетей терр.компл.застр.р-на ул.Б.Хмельн.','ВР_2011',0,'',0,'','Строительство инженерных сетей и сооружений территории комплексной застройки района улицы Богдана Хмельницкого (Чувашская Республика)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'483',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро "Монолит", г. Городец, Нижегородская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро "Монолит", г. Городец, Нижегородская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'484',@link_self,'Взнос в уставный капитал открытого акционерного общества "Российская корпорация ракетно-космического приборостроения и информационных систем", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Российская корпорация ракетно-космического приборостроения и информационных систем", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'485',@link_self,'Массовая малоэтажная застройка в с.Воскресенское','ВР_2011',0,'',0,'','Массовая малоэтажная застройка в с. Воскресенское Ферзиковского района Калужской области',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'489',@link_self,'Взнос в уставный капитал открытого акционерного общества "Федеральная гидрогенерирующая компания", г. Красноярск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Федеральная гидрогенерирующая компания", г. Красноярск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'494',@link_self,'Взнос в уставный капитал открытого акционерного общества "Завод № 9", г. Екатеринбург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Завод № 9", г. Екатеринбург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'498',@link_self,'Разв.с-мы теплоснабжения в г.Владимир и Влад.обл.','ВР_2011',0,'',0,'','Развитие системы теплоснабжения в г. Владимир и Владимирской области',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'500',@link_self,'Межбюджетные трансферты','ВР_2011',0,'',0,'','Межбюджетные трансферты',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Межбюджетные трансферты', 'Межбюджетные трансферты', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'501',@link_self,'Стр-во и реконстр.водопр.оч.сооруж.г.Петрозаводска','ВР_2011',0,'',0,'','Строительство и реконструкция водопроводных очистных сооружений г. Петрозаводска (II этап)',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'510',@link_self,'Дотации на выравнивание бюджетной обеспеченности','ВР_2011',0,'',0,'','Дотации на выравнивание бюджетной обеспеченности','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Дотации на выравнивание бюджетной обеспеченности', 'Дотации на выравнивание бюджетной обеспеченности', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Дотации', 'Дотации', '20000101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '510' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'511',@link_self,'Дотации на выравнивание бюджетной обеспеченности субъектов Российской Федерации','ВР_2011',0,'',0,'','Дотации на выравнивание бюджетной обеспеченности субъектов Российской Федерации','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '510' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'512',@link_self,'Иные дотации','ВР_2011',0,'',0,'','Иные дотации','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Дотации бюджетам субъектов Российской Федерации на поддержку мер по обеспечению сбалансированности бюджетов', 'Дотации бюджетам субъектов Российской Федерации на поддержку мер по обеспечению сбалансированности бюджетов', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Иные дотации', 'Иные дотации', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '510' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'513',@link_self,'Дотации бюджетам закрытых административно-территориальных образований, связанные со статусом закрытых административно-территориальных образований','ВР_2011',0,'',0,'','Дотации бюджетам закрытых административно-территориальных образований, связанные со статусом закрытых административно-территориальных образований','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '510' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'514',@link_self,'Дотации бюджету города Байконура','ВР_2011',0,'',0,'','Дотации бюджету города Байконура','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'517',@link_self,'Взнос в уставный капитал открытого акционерного общества "Сахалинская энергетическая компания", г. Южно-Сахалинск, Сахалинская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Сахалинская энергетическая компания", г. Южно-Сахалинск, Сахалинская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'520',@link_self,'Субсидии','ВР_2011',0,'',0,'','Субсидии','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии', 'Субсидии', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '520' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'521',@link_self,'Субсидии, за исключением субсидий на софинансирование капитальных вложений в объект государственной (муниципальной) собственности','ВР_2011',0,'',0,'','Субсидии, за исключением субсидий на софинансирование капитальных вложений в объект государственной (муниципальной) собственности','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии, за исключением субсидий на софинансирование капитальных вложений в объект государственной (муниципальной) собственности', 'Субсидии, за исключением субсидий на софинансирование капитальных вложений в объект государственной (муниципальной) собственности', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии, за исключением субсидий на софинансирование объектов капитального строительства государственной собственности и муниципальной собственности', 'Субсидии, за исключением субсидий на софинансирование объектов капитального строительства государственной собственности и муниципальной собственности', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '520' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'522',@link_self,'Субсидии на софинансирование капитальных вложений в объект государственной (муниципальной) собственности','ВР_2011',0,'',0,'','Субсидии на софинансирование капитальных вложений в объект государственной (муниципальной) собственности','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на софинансирование капитальных вложений в объект государственной (муниципальной) собственности', 'Субсидии на софинансирование капитальных вложений в объект государственной (муниципальной) собственности', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии на софинансирование объектов капитального строительства государственной (муниципальной) собственности', 'Субсидии на софинансирование объектов капитального строительства государственной (муниципальной) собственности', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'523',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт точных приборов", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт точных приборов", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'524',@link_self,'Взнос в уставный капитал открытого акционерного общества "Особое конструкторское бюро Московского энергетического института", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Особое конструкторское бюро Московского энергетического института", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'525',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение измерительной техники", г. Королев, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение измерительной техники", г. Королев, Московская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'527',@link_self,'Взнос в уставный капитал открытого акционерного общества "Ордена Ленина Научно-исследовательский и конструкторский институт энерготехники имени Н.А. Доллежаля", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Ордена Ленина Научно-исследовательский и конструкторский институт энерготехники имени Н.А. Доллежаля", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'528',@link_self,'Взнос в уставный капитал открытого акционерного общества "Завод "Топаз", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Завод "Топаз", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'529',@link_self,'Взнос в уставный капитал открытого акционерного общества "Невское проектно-конструкторское бюро", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Невское проектно-конструкторское бюро", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'530',@link_self,'Субвенции','ВР_2011',0,'',0,'','Субвенции',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субвенции', 'Субвенции', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'531',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро "Лазурит", г. Нижний Новгород','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральное конструкторское бюро "Лазурит", г. Нижний Новгород',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'532',@link_self,'Взнос в уставный капитал открытого акционерного общества "Ангарский электролизный химический комбинат", г. Ангарск, Иркутская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Ангарский электролизный химический комбинат", г. Ангарск, Иркутская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'533',@link_self,'Взнос в уставный капитал открытого акционерного общества "Новосибирский завод химконцентратов", г. Новосибирск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Новосибирский завод химконцентратов", г. Новосибирск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'534',@link_self,'Взнос в уставный капитал открытого акционерного общества "Приаргунское производственное горно-химическое объединение", г. Краснокаменск, Забайкальский край','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Приаргунское производственное горно-химическое объединение", г. Краснокаменск, Забайкальский край',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'535',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение электромеханики", г. Миасс, Челябинская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение электромеханики", г. Миасс, Челябинская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'536',@link_self,'Закупка специальных изделий и оборудования в целях обеспечения системы управления безопасностью полетов','ВР_2011',0,'',0,'','Закупка специальных изделий и оборудования в целях обеспечения системы управления безопасностью полетов',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'537',@link_self,'Взнос Российской Федерации в уставный капитал открытого акционерного общества "Производственное объединение "Северное машиностроительное предприятие" путем размещения дополнительных акций','ВР_2011',0,'',0,'','Взнос Российской Федерации в уставный капитал открытого акционерного общества "Производственное объединение "Северное машиностроительное предприятие" путем размещения дополнительных акций',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'539',@link_self,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Уральский оптико-механический завод" имени Э.С. Яламова", г. Екатеринбург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Уральский оптико-механический завод" имени Э.С. Яламова", г. Екатеринбург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'540',@link_self,'Иные межбюджетные трансферты','ВР_2011',0,'',0,'','Иные межбюджетные трансферты',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные межбюджетные трансферты', 'Иные межбюджетные трансферты', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'550',@link_self,'Межбюджетные трансферты бюджету Фонда социального страхования Российской Федерации','ВР_2011',0,'',0,'','Межбюджетные трансферты бюджету Фонда социального страхования Российской Федерации',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Межбюджетные трансферты бюджету Фонда социального страхования Российской Федерации', 'Межбюджетные трансферты бюджету Фонда социального страхования Российской Федерации', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'553',@link_self,'Субсидии некоммерческим организациям в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта','ВР_2011',0,'',0,'','Субсидии некоммерческим организациям в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'554',@link_self,'Софинансирование объектов капитального строительства государственной собственности субъектов Российской Федерации (объектов капитального строительства собственности муниципальных образований) в рамках организации и проведения ХХII Олимпийских зимних','ВР_2011',0,'',0,'','Софинансирование объектов капитального строительства государственной собственности субъектов Российской Федерации (объектов капитального строительства собственности муниципальных образований) в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'557',@link_self,'Выполнение функций бюджетными учреждениями в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта','ВР_2011',0,'',0,'','Выполнение функций бюджетными учреждениями в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'558',@link_self,'Взнос в уставный капитал открытого акционерного общества "Холдинг межрегиональных распределительных сетевых компаний" (г. Москва) в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, ра','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Холдинг межрегиональных распределительных сетевых компаний" (г. Москва) в рамках организации и проведения ХХII Олимпийских зимних игр и ХI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'559',@link_self,'Функционирование Вооруженных сил Российской Федерации, органов в сфере национальной безопасности и правоохранительной деятельности, войск и иных воинских формирований в рамках организации и проведения XXII Олимпийских зимних игр и XI Паралимпийских з','ВР_2011',0,'',0,'','Функционирование Вооруженных сил Российской Федерации, органов в сфере национальной безопасности и правоохранительной деятельности, войск и иных воинских формирований в рамках организации и проведения XXII Олимпийских зимних игр и XI Паралимпийских зимних игр 2014 года в городе Сочи, развития города Сочи как горноклиматического курорта',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'560',@link_self,'Межбюджетные трансферты бюджету Федерального фонда обязательного медицинского страхования','ВР_2011',0,'',0,'','Межбюджетные трансферты бюджету Федерального фонда обязательного медицинского страхования','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'570',@link_self,'Межбюджетные трансферты бюджету Пенсионного фонда Российской Федерации','ВР_2011',0,'',0,'','Межбюджетные трансферты бюджету Пенсионного фонда Российской Федерации','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '500' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'580',@link_self,'Межбюджетные трансферты бюджетам территориальных фондов обязательного медицинского страхования','ВР_2011',0,'',0,'','Межбюджетные трансферты бюджетам территориальных фондов обязательного медицинского страхования','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'585',@link_self,'Финансирование расходов, осуществляемое за счет средств, поступающих от привлечения осужденных к труду','ВР_2011',0,'',0,'','Финансирование расходов, осуществляемое за счет средств, поступающих от привлечения осужденных к труду','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'590',@link_self,'Взнос в уставный капитал открытого акционерного общества "Московский завод "Сапфир", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Московский завод "Сапфир", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'591',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-производственный комплекс "Технокомплекс", г. Раменское, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-производственный комплекс "Технокомплекс", г. Раменское, Московская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'592',@link_self,'Взнос в уставный капитал открытого акционерного общества "РЭ Комплексные системы", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "РЭ Комплексные системы", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'593',@link_self,'Взнос в уставный капитал открытого акционерного общества завод "Красное знамя", г. Рязань','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества завод "Красное знамя", г. Рязань',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'594',@link_self,'Взнос в уставный капитал открытого акционерного общества "Уральское производственное предприятие "Вектор", г. Екатеринбург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Уральское производственное предприятие "Вектор", г. Екатеринбург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'595',@link_self,'Взнос в уставный капитал открытого акционерного общества "Завод "Метеор", г. Волжский, Волгоградская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Завод "Метеор", г. Волжский, Волгоградская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'596',@link_self,'Взнос в уставный капитал открытого акционерного общества "Холдинговая компания "Новосибирский электровакуумный завод - Союз", г. Новосибирск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Холдинговая компания "Новосибирский электровакуумный завод - Союз", г. Новосибирск',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'597',@link_self,'Взнос в уставный капитал открытого акционерного общества "Богородицкий завод технохимических изделий", г. Богородицк, Тульская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Богородицкий завод технохимических изделий", г. Богородицк, Тульская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'598',@link_self,'Взнос в уставный капитал открытого акционерного общества "Специальное конструкторско-технологическое бюро по релейной технике", г. Великий Новгород','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Специальное конструкторско-технологическое бюро по релейной технике", г. Великий Новгород',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'599',@link_self,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Азимут", г. Махачкала, Республика Дагестан','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Азимут", г. Махачкала, Республика Дагестан',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'600',@link_self,'Предоставление субсидий бюджетным, автономным учреждениям и иным некоммерческим организациям','ВР_2011',0,'',0,'','Предоставление субсидий бюджетным, автономным учреждениям и иным некоммерческим организациям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Предоставление субсидий бюджетным, автономным учреждениям и иным некоммерческим организациям', 'Предоставление субсидий бюджетным, автономным учреждениям и иным некоммерческим организациям', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Предоставление субсидий федеральным бюджетным, автономным учреждениям и иным некоммерческим организациям', 'Предоставление субсидий федеральным бюджетным, автономным учреждениям и иным некоммерческим организациям', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'601',@link_self,'Взнос в уставный капитал открытого акционерного общества "Российский научно-исследовательский институт "Электронстандарт", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Российский научно-исследовательский институт "Электронстандарт", г. Санкт-Петербург',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'602',@link_self,'Взнос в уставный капитал открытого акционерного общества "Холдинговая компания "Станкоинструмент", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Холдинговая компания "Станкоинструмент", г. Москва',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'603',@link_self,'Взнос в уставный капитал открытого акционерного общества "РАО Энергетические системы Востока", г. Благовещенск, Амурская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "РАО Энергетические системы Востока", г. Благовещенск, Амурская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'604',@link_self,'Взнос в уставный капитал открытого акционерного общества "Колымаэнерго", г. Магадан, Магаданская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Колымаэнерго", г. Магадан, Магаданская область',NULL,'20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'605',@link_self,'Взнос в уставный капитал открытого акционерного общества  "15 центральный автомобильный ремонтный завод", г. Новосибирск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "15 центральный автомобильный ремонтный завод", г. Новосибирск','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'606',@link_self,'Взнос в уставный капитал открытого акционерного общества  "172 центральный автомобильный ремонтный завод", г. Воронеж','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "172 центральный автомобильный ремонтный завод", г. Воронеж','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'607',@link_self,'Взнос в уставный капитал открытого акционерного общества  "81 бронетанковый ремонтный завод", г. Армавир, Краснодарский край','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "81 бронетанковый ремонтный завод", г. Армавир, Краснодарский край','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'608',@link_self,'Взнос в уставный капитал открытого акционерного общества  "103 бронетанковый ремонтный завод", г. пос. Атамановское, Забайкальский край','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "103 бронетанковый ремонтный завод", г. пос. Атамановское, Забайкальский край','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'609',@link_self,'Взнос в уставный капитал открытого акционерного общества  "163 бронетанковый ремонтный завод", ст-ца Кущевская, Краснодарский край','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "163 бронетанковый ремонтный завод", ст-ца Кущевская, Краснодарский край','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '600' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'610',@link_self,'Субсидии бюджетным учреждениям','ВР_2011',0,'',0,'','Субсидии бюджетным учреждениям','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии бюджетным учреждениям', 'Субсидии бюджетным учреждениям', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '610' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'611',@link_self,'Субсидии бюджетным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)','ВР_2011',0,'',0,'','Субсидии бюджетным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии бюджетным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)', 'Субсидии бюджетным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии бюджетным учреждениям на финансовое обеспечение государственного задания на оказание государственных услуг (выполнение работ)', 'Субсидии бюджетным учреждениям на финансовое обеспечение государственного задания на оказание государственных услуг (выполнение работ)', '20000101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '610' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'612',@link_self,'Субсидии бюджетным учреждениям на иные цели','ВР_2011',0,'',0,'','Субсидии бюджетным учреждениям на иные цели','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'615',@link_self,'Взнос в уставный капитал открытого акционерного общества холдинговая компания "Авиаприбор-холдинг", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества холдинговая компания "Авиаприбор-холдинг", г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'616',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Научно-производственное объединение "Альфа", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Научно-производственное объединение "Альфа", г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'617',@link_self,'Взнос в уставный капитал открытого акционерного общества "Воткинский завод", г. Воткинск, Удмуртская Республика','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Воткинский завод", г. Воткинск, Удмуртская Республика','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'618',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Вольский механический завод", г. Вольск, Саратовская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Вольский механический завод", г. Вольск, Саратовская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'619',@link_self,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Новосибирский приборостроительный завод", г. Новосибирск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Новосибирский приборостроительный завод", г. Новосибирск','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '600' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'620',@link_self,'Субсидии автономным учреждениям','ВР_2011',0,'',0,'','Субсидии автономным учреждениям','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии автономным учреждениям', 'Субсидии автономным учреждениям', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '620' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'621',@link_self,'Субсидии автономным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)','ВР_2011',0,'',0,'','Субсидии автономным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии автономным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)', 'Субсидии автономным учреждениям на финансовое обеспечение государственного (муниципального) задания на оказание государственных (муниципальных) услуг (выполнение работ)', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии автономным учреждениям на финансовое обеспечение государственного задания на оказание государственных услуг (выполнение работ)', 'Субсидии автономным учреждениям на финансовое обеспечение государственного задания на оказание государственных услуг (выполнение работ)', '20120101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '620' and begin_date ='19000101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'622',@link_self,'Субсидии автономным учреждениям на иные цели','ВР_2011',0,'',0,'','Субсидии автономным учреждениям на иные цели','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии автономным учреждениям на иные цели', 'Субсидии автономным учреждениям на иные цели', '20120101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'623',@link_self,'Взнос в уставный капитал открытого акционерного общества "Калужский научно-исследовательский институт телемеханических устройств", г. Калуга','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Калужский научно-исследовательский институт телемеханических устройств", г. Калуга','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'624',@link_self,'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт "Вектор", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт "Вектор", г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'625',@link_self,'Взнос в уставный капитал открытого акционерного общества "Информационные телекоммуникационные технологии", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Информационные телекоммуникационные технологии", г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'626',@link_self,'Взнос в уставный капитал открытого акционерного общества "Миасский машиностроительный завод", г. Миасс, Челябинская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Миасский машиностроительный завод", г. Миасс, Челябинская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'627',@link_self,'Взнос в уставный капитал открытого акционерного общества "Златоустовский машиностроительный завод", г. Златоуст, Челябинская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Златоустовский машиностроительный завод", г. Златоуст, Челябинская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'628',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Научно-исследовательский институт "Субмикрон", г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Научно-исследовательский институт "Субмикрон", г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'629',@link_self,'Взнос в уставный капитал открытого акционерного общества "Протон - Пермские моторы", г. Пермь','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Протон - Пермские моторы", г. Пермь','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '600' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'630',@link_self,'Субсидии некоммерческим организациям (за исключением государственных (муниципальных) учреждений)','ВР_2011',0,'',0,'','Субсидии некоммерческим организациям (за исключением государственных (муниципальных) учреждений)','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии некоммерческим организациям  (за исключением государственных учреждений)', 'Субсидии некоммерческим организациям  (за исключением государственных учреждений)', '20120101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии некоммерческим организациям (за исключением государственных (муниципальных) учреждений)', 'Субсидии некоммерческим организациям (за исключением государственных (муниципальных) учреждений)', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии некоммерческим организациям (за исключением государственных учреждений)', 'Субсидии некоммерческим организациям (за исключением государственных учреждений)', '20130101'
        

GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'631',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Спецтехника", ЗАТО "Озерный", Тверская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Спецтехника", ЗАТО "Озерный", Тверская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'632',@link_self,'Взнос в уставный капитал открытого акционерного общества  "190 Центральный ремонтный завод средств связи",  г. Рыбинск, Ярославская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "190 Центральный ремонтный завод средств связи",  г. Рыбинск, Ярославская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'633',@link_self,'Взнос в уставный капитал открытого акционерного общества "Хабаровский радиотехнический завод", г. Хабаровск','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Хабаровский радиотехнический завод", г. Хабаровск','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'634',@link_self,'Взнос в уставный капитал открытого акционерного общества  "9 центральный автомобильный ремонтный завод", г. Энгельс, Саратовская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "9 центральный автомобильный ремонтный завод", г. Энгельс, Саратовская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'635',@link_self,'Взнос в уставный капитал открытого акционерного общества "Воронежский Завод Полупроводниковых Приборов - Сборка", г. Воронеж','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Воронежский Завод Полупроводниковых Приборов - Сборка", г. Воронеж','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'636',@link_self,'Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт материалов", г. Санкт-Петербург','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Центральный научно-исследовательский институт материалов", г. Санкт-Петербург','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'637',@link_self,'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Баррикады",  г. Волгоград, Волгоградская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Баррикады",  г. Волгоград, Волгоградская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'638',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Центральное конструкторское бюро "Титан", г. Волгоград, Волгоградская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Центральное конструкторское бюро "Титан", г. Волгоград, Волгоградская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'639',@link_self,'Взнос в уставный капитал открытого акционерного общества "Иркутский релейный завод", г. Иркутск, Иркутская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Иркутский релейный завод", г. Иркутск, Иркутская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'640',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Корпорация "Московский институт теплотехники" г. Москва','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Корпорация "Московский институт теплотехники" г. Москва','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'641',@link_self,'Взнос в уставный капитал открытого акционерного общества  "Головное особое конструкторское бюро "Прожектор", г. Москва".','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества  "Головное особое конструкторское бюро "Прожектор", г. Москва".','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'643',@link_self,'Взнос в уставный капитал открытого акционерного общества "Особое конструкторское бюро кабельной промышленности", г. Мытищи, Московская область','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества "Особое конструкторское бюро кабельной промышленности", г. Мытищи, Московская область','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'644',@link_self,'Взнос в уставный капитал открытого акционерного общества"Научно-исследовательский и технологический институт оптического материаловедения Всероссийского научного центра "Государственныйоптический институт им. С.И. Вавилова", г. Санкт-Петербург".','ВР_2011',0,'',0,'','Взнос в уставный капитал открытого акционерного общества"Научно-исследовательский и технологический институт оптического материаловедения Всероссийского научного центра "Государственныйоптический институт им. С.И. Вавилова", г. Санкт-Петербург".','19000101','20111231'
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'700',@link_self,'Обслуживание государственного (муниципального) долга','ВР_2011',0,'',0,'','Обслуживание государственного (муниципального) долга','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Обслуживание государственного (муниципального) долга', 'Обслуживание государственного (муниципального) долга', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Обслуживание государственного долга Российской Федерации', 'Обслуживание государственного долга Российской Федерации', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '700' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'710',@link_self,'Обслуживание государственного долга Российской Федерации','ВР_2011',0,'',0,'','Обслуживание государственного долга Российской Федерации','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Обслуживание государственного долга Российской Федерации', 'Обслуживание государственного долга Российской Федерации', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '000' and begin_date  is NULL and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'800',@link_self,'Иные бюджетные ассигнования','ВР_2011',0,'',0,'','Иные бюджетные ассигнования','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные бюджетные ассигнования', 'Иные бюджетные ассигнования', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'810',@link_self,'Субсидии юридическим лицам (кроме некоммерческих организаций), индивидуальным предпринимателям, физическим лицам','ВР_2011',0,'',0,'','Субсидии юридическим лицам (кроме некоммерческих организаций), индивидуальным предпринимателям, физическим лицам','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии юридическим лицам (кроме государственных учреждений)  и физическим лицам - производителям товаров, работ, услуг', 'Субсидии юридическим лицам (кроме государственных учреждений)  и физическим лицам - производителям товаров, работ, услуг', '20130101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии юридическим лицам (кроме некоммерческих организаций), индивидуальным предпринимателям, физическим лицам', 'Субсидии юридическим лицам (кроме некоммерческих организаций), индивидуальным предпринимателям, физическим лицам', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'820',@link_self,'Субсидии государственным корпорациям (компаниям)','ВР_2011',0,'',0,'','Субсидии государственным корпорациям (компаниям)','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии государственным корпорациям (компаниям)', 'Субсидии государственным корпорациям (компаниям)', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '820' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'821',@link_self,'Субсидии государственным корпорациям (компаниям) в виде имущественного взноса','ВР_2011',0,'',0,'','Субсидии государственным корпорациям (компаниям) в виде имущественного взноса','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии государственным корпорациям (компаниям) в виде имущественного взноса', 'Субсидии государственным корпорациям (компаниям) в виде имущественного взноса', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '820' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'822',@link_self,'Субсидии государственным корпорациям (компаниям) на выполнение возложенных на них государственных полномочий','ВР_2011',0,'',0,'','Субсидии государственным корпорациям (компаниям) на выполнение возложенных на них государственных полномочий','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Субсидии государственным корпорациям (компаниям) на выполнение возложенных на них государственных полномочий', 'Субсидии государственным корпорациям (компаниям) на выполнение возложенных на них государственных полномочий', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '820' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'823',@link_self,'Иные субсидии государственным корпорациям (компаниям)','ВР_2011',0,'',0,'','Иные субсидии государственным корпорациям (компаниям)','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Иные субсидии государственным корпорациям (компаниям)', 'Иные субсидии государственным корпорациям (компаниям)', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'830',@link_self,'Исполнение судебных актов','ВР_2011',0,'',0,'','Исполнение судебных актов','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение судебных актов', 'Исполнение судебных актов', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '830' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'831',@link_self,'Исполнение судебных актов Российской Федерации и мировых соглашений по возмещению вреда, причиненного в результате незаконных действий (бездействия) органов государственной власти (государственных органов), органов местного самоуправления либо должно','ВР_2011',0,'',0,'','Исполнение судебных актов Российской Федерации и мировых соглашений по возмещению вреда, причиненного в результате незаконных действий (бездействия) органов государственной власти (государственных органов), органов местного самоуправления либо должностных','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение судебных актов Российской Федерации и мировых соглашений по возмещению вреда, причиненного в результате  незаконных действий (бездействия) органов государственной власти (государственных органов) либо должностных лиц этих органов,  а также в з', 'Исполнение судебных актов Российской Федерации и мировых соглашений по возмещению вреда, причиненного в результате  незаконных действий (бездействия) органов государственной власти (государственных органов) либо должностных лиц этих органов,  а также в результате деятельности казенных учреждений', '20130101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение судебных актов Российской Федерации и мировых соглашений по возмещению вреда, причиненного в результате незаконных действий (бездействия) органов государственной власти (государственных органов), органов местного самоуправления либо должно', 'Исполнение судебных актов Российской Федерации и мировых соглашений по возмещению вреда, причиненного в результате незаконных действий (бездействия) органов государственной власти (государственных органов), органов местного самоуправления либо должностных', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '830' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'832',@link_self,'Исполнение судебных актов судебных органов иностранных государств, международных судов и арбитражей, определяемых международными договорами Российской Федерации, в результате незаконных действий (бездействия) органов государственной власти (государст','ВР_2011',0,'',0,'','Исполнение судебных актов судебных органов иностранных государств, международных судов и арбитражей, определяемых международными договорами Российской Федерации, в результате незаконных действий (бездействия) органов государственной власти (государственных органов) либо должностных лиц этих органов, мировых соглашений, заключенных  в рамках судебных процессов в судебных органах иностранных государств,  в международных судах и арбитражах','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение судебных актов судебных органов иностранных государств, международных судов и арбитражей, определяемых международными договорами Российской Федерации, в результате незаконных действий (бездействия) органов государственной власти (государственх', 'Исполнение судебных актов судебных органов иностранных государств, международных судов и арбитражей, определяемых международными договорами Российской Федерации, в результате незаконных действий (бездействия) органов государственной власти (государственных органов) либо должностных лиц этих органов, мировых соглашений, заключенных  в рамках судебных процессов в судебных органах иностранных государств,  в международных судах и арбитражах', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'840',@link_self,'Исполнение государственных (муниципальных) гарантий без права регрессного требования гаранта к принципалу или уступки гаранту прав требования бенефициара к принципалу','ВР_2011',0,'',0,'','Исполнение государственных (муниципальных) гарантий без права регрессного требования гаранта к принципалу или уступки гаранту прав требования бенефициара к принципалу','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение государственных (муниципальных) гарантий без права регрессного требования гаранта к принципалу или уступки гаранту прав требования бенефициара к принципалу', 'Исполнение государственных (муниципальных) гарантий без права регрессного требования гаранта к принципалу или уступки гаранту прав требования бенефициара к принципалу', '20140206'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение государственных гарантий без права регрессного требования гаранта к принципалу или уступки гаранту прав требования бенефициара к принципалу', 'Исполнение государственных гарантий без права регрессного требования гаранта к принципалу или уступки гаранту прав требования бенефициара к принципалу', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '840' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'841',@link_self,'Исполнение государственных гарантий Российской Федерации','ВР_2011',0,'',0,'','Исполнение государственных гарантий Российской Федерации','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение государственных гарантий Российской Федерацией', 'Исполнение государственных гарантий Российской Федерацией', '20130101'
        
exec dbo.RO_KBK_HIST_SAVE @link, 'Исполнение государственных гарантий Российской Федерации', 'Исполнение государственных гарантий Российской Федерации', '20140206'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'850',@link_self,'Уплата налогов, сборов и иных платежей','ВР_2011',0,'',0,'','Уплата налогов, сборов и иных платежей','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Уплата налогов, сборов и иных платежей', 'Уплата налогов, сборов и иных платежей', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '850' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'851',@link_self,'Уплата налога на имущество организаций и земельного налога','ВР_2011',0,'',0,'','Уплата налога на имущество организаций и земельного налога','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Уплата налога на имущество организаций и земельного налога', 'Уплата налога на имущество организаций и земельного налога', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '850' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'852',@link_self,'Уплата прочих налогов, сборов и иных платежей','ВР_2011',0,'',0,'','Уплата прочих налогов, сборов и иных платежей','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Уплата прочих налогов, сборов и иных платежей', 'Уплата прочих налогов, сборов и иных платежей', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'860',@link_self,'Предоставление платежей, взносов, безвозмездных перечислений субъектам международного права','ВР_2011',0,'',0,'','Предоставление платежей, взносов, безвозмездных перечислений субъектам международного права','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Предоставление платежей, взносов, безвозмездных перечислений субъектам международного права', 'Предоставление платежей, взносов, безвозмездных перечислений субъектам международного права', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '860' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'861',@link_self,'Безвозмездные перечисления субъектам международного права','ВР_2011',0,'',0,'','Безвозмездные перечисления субъектам международного права','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Безвозмездные перечисления субъектам международного права', 'Безвозмездные перечисления субъектам международного права', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '860' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'862',@link_self,'Взносы в международные организации','ВР_2011',0,'',0,'','Взносы в международные организации','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Взносы в международные организации', 'Взносы в международные организации', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '860' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'863',@link_self,'Платежи в целях обеспечения реализации соглашений с правительствами иностранных государств и международными организациями','ВР_2011',0,'',0,'','Платежи в целях обеспечения реализации соглашений с правительствами иностранных государств и международными организациями','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Платежи в целях обеспечения реализации соглашений с правительствами иностранных государств и международными организациями', 'Платежи в целях обеспечения реализации соглашений с правительствами иностранных государств и международными организациями', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'870',@link_self,'Резервные средства','ВР_2011',0,'',0,'','Резервные средства','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Резервные средства', 'Резервные средства', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '800' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'880',@link_self,'Специальные расходы','ВР_2011',0,'',0,'','Специальные расходы','20120101',NULL
delete dbo.report_kbk_hist where link_up = @link

exec dbo.RO_KBK_HIST_SAVE @link, 'Специальные расходы', 'Специальные расходы', '20130101'
        

GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '120' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'123',@link_self,'Иные выплаты, за исключением фонда оплаты труда государственных (муниципальных) органов, лицам, привлекаемым согласно законодательству для выполнения отдельных полномочий','ВР_2011',0,'',0,'','Иные выплаты, за исключением фонда оплаты труда государственных (муниципальных) органов, лицам, привлекаемым согласно законодательству для выполнения отдельных полномочий','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '450' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'451',@link_self,'Бюджетные инвестиции иным юридическим лицам в объекты капитального строительства','ВР_2011',0,'',0,'','Бюджетные инвестиции иным юридическим лицам в объекты капитального строительства','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '450' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'452',@link_self,'Бюджетные инвестиции иным юридическим лицам, за исключением бюджетных инвестиций в объекты капитального строительства','ВР_2011',0,'',0,'','Бюджетные инвестиции иным юридическим лицам, за исключением бюджетных инвестиций в объекты капитального строительства','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '700' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'720',@link_self,'Обслуживание государственного долга Российской Федерации','ВР_2011',0,'',0,'','Обслуживание государственного долга Российской Федерации','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '700' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'730',@link_self,'Обслуживание муниципального долга','ВР_2011',0,'',0,'','Обслуживание муниципального долга','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '840' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'842',@link_self,'Исполнение государственных гарантий субъекта Российской Федерации','ВР_2011',0,'',0,'','Исполнение государственных гарантий субъекта Российской Федерации','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '840' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'843',@link_self,'Исполнение муниципальных гарантий','ВР_2011',0,'',0,'','Исполнение муниципальных гарантий','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '400' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'460',@link_self,'Субсидии на осуществление капитальных вложений бюджетным и автономным учреждениям, государственным (муниципальным) унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений бюджетным и автономным учреждениям, государственным (муниципальным) унитарным предприятиям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '460' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'461',@link_self,'Субсидии  на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность бюджетным учреждениям','ВР_2011',0,'',0,'','Субсидии  на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность бюджетным учреждениям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '460' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'462',@link_self,'Субсидии на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность автономным учреждениям','ВР_2011',0,'',0,'','Субсидии на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность автономным учреждениям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '460' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'463',@link_self,'Субсидии на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность государственным (муниципальным) унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на приобретение объектов недвижимого имущества в государственную (муниципальную) собственность государственным (муниципальным) унитарным предприятиям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '460' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'464',@link_self,'Субсидии на осуществление капитальных вложений в объекты капитального строительства государственной (муниципальной) собственности бюджетным учреждениям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений в объекты капитального строительства государственной (муниципальной) собственности бюджетным учреждениям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '460' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'465',@link_self,'Субсидии на осуществление капитальных вложений в объекты капитального строительства государственной (муниципальной) собственности автономным учреждениям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений в объекты капитального строительства государственной (муниципальной) собственности автономным учреждениям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '460' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'466',@link_self,'Субсидии на осуществление капитальных вложений в объекты капитального строительства государственной (муниципальной) собственности государственным (муниципальным) унитарным предприятиям','ВР_2011',0,'',0,'','Субсидии на осуществление капитальных вложений в объекты капитального строительства государственной (муниципальной) собственности государственным (муниципальным) унитарным предприятиям','20140101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '110' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'119',@link_self,'Взносы по обязательному социальному страхованию  на выплаты по оплате труда работников и иные выплаты работникам учреждений','ВР_2011',0,'',0,'','Взносы по обязательному социальному страхованию  на выплаты по оплате труда работников и иные выплаты работникам учреждений','20160101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '120' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'129',@link_self,'Взносы по обязательному социальному страхованию на выплаты денежного содержания и иные выплаты работникам государственных (муниципальных) органов','ВР_2011',0,'',0,'','Взносы по обязательному социальному страхованию на выплаты денежного содержания и иные выплаты работникам государственных (муниципальных) органов','20160101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '140' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'149',@link_self,'Взносы по обязательному социальному страхованию на выплаты по оплате труда работников и иные выплаты работникам государственных внебюджетных фондов','ВР_2011',0,'',0,'','Взносы по обязательному социальному страхованию на выплаты по оплате труда работников и иные выплаты работникам государственных внебюджетных фондов','20160101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'416',@link_self,'Капитальные вложения на приобретение объектов недвижимого имущества государственными (муниципальными) учреждениями','ВР_2011',0,'',0,'','Капитальные вложения на приобретение объектов недвижимого имущества государственными (муниципальными) учреждениями','20160101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '410' and begin_date ='20140101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'417',@link_self,'Капитальные вложения на строительство объектов недвижимого имущества государственными (муниципальными) учреждениями','ВР_2011',0,'',0,'','Капитальные вложения на строительство объектов недвижимого имущества государственными (муниципальными) учреждениями','20160101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO
declare @link_self int, @link int 
select @link_self = Link from report_kbk where Code_Form = 'ВР_2011' and  Code = '820' and begin_date ='20120101' and end_date  is NULL
exec RN_SAVE_REPORT_KBK @link output,'824',@link_self,'Субсидии государственным корпорациям (компаниям) на иные цели','ВР_2011',0,'',0,'','Субсидии государственным корпорациям (компаниям) на иные цели','20160101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO

GO


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

GO

/*

	c Кейсистемс (Keysystems), 2010
	Печать форм 127 (для параметра "все атрибуты в один отчет)
	Печать с подитогами
*/


CREATE       PROCEDURE dbo.RO_PRINT_127_ITOG_16
	@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

declare @varKSiParam int, -- 0 - без подитогов, 1 бит - подитоги по ЭКР, 2 бит - подитоги по ВР, 3 бит - подитоги по ЦСР, 4 бит - подитоги по подразделу, 5 бит - подитоги по раздеру, 6 бит - подитоги по администратору
		@varKSiNoItog int, @iYear INT, @vcAtr VARCHAR(50), @varKSiRashEKR TINYINT, @varKSiNoItogRash TINYINT

SET @vcAtr = dbo.RN_GET_ATR_VALUE(@LSF, 'REPORTS_ATR_ADM')

set @varKSiParam = 0
set @varKSiNoItog = 0
SET @varKSiRashEKR = 3
SET @varKSiNoItogRash = 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'
select @varKSiRashEKR = convert(int, Value) from #Param_Print where Param = 'RASH_EKR'
select @varKSiNoItogRash = convert(int, Value) from #Param_Print where Param = 'NoItog_Rash'
END


if isnull(@varKSiNoItog,0) = 1
begin
	exec dbo.RO_PRINT_NO_ITOG @LSF, @bDeleteEmptyRows, @data, @notNullCol, @AtrInOnePage, @WEB_excel
	return
end


IF @LSF is NULL
	return -1

declare @iLF int, @iLT INT, @dBeginDate DATETIME
select @iLF = Link_Form, @iYear = YEAR(begin_date), @dBeginDate = Begin_Date
from report_saved_forms where Link_Saved_Form = @LSF

if isnull(@WEB_excel, 0) <> 1
	select '' col1

-- таблица доходы
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(1500), Col2 varchar(1000), Col3 varchar(1000),  Col4 float, Col5 float, Col6 float, Col7 float, Col8 float, Col9 float)

insert #doh (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9)
exec dbo.rn_get_all_adm_table 	@LSF, 1, @bDeleteEmptyRows, @AtrInOnePage, 1

IF NOT EXISTS(SELECT * FROM #doh)
BEGIN
insert #doh (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9)
SELECT 0, 0, 0, @LSF, 0, -1, 0, 0, '00085000000000000000', 'Доходы - всего', '010', '85000000000000000', 0, 0, 0, 0, 0, 0
END

SELECT * FROM #doh


------------------------------------------------------------------------------------------------
--- ТАБЛИЦА РАСХОДЫ С ПОДИТОГАМИ
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(1500), Col2 varchar(1000), Col3 varchar(1000), Col4 varchar(1000), Col5 varchar(1000), Col6 float, Col7 float, Col8 float, Col9 float, Col10 float, Col11 float, Col12 float, Col13 float, Col14 varchar(50))

select * into #rash_itog from #rash

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)
exec dbo.rn_get_all_adm_table 	@LSF, 2, @bDeleteEmptyRows, @AtrInOnePage, 1



IF @varKSiRashEKR = 1
BEGIN
UPDATE #rash
SET COL6 = 0,
COL7 = 0,
COL12 = 0,
COL13 = 0
WHERE RIGHT(RTRIM(CODE),3) <> '000'
END

IF @varKSiRashEKR = 2
BEGIN
UPDATE #rash
SET COL6 = 0,
COL7 = 0,
COL12 = 0,
COL13 = 0
WHERE RIGHT(RTRIM(CODE),2) <> '00'
END

IF @varKSiNoItogRash = 1
BEGIN
DELETE #rash
WHERE RIGHT(RTRIM(CODE),3) IN ('200', '210', '220', '230', '240', '250', '260', '300', '500', '600')

IF @varKSiParam = 0
BEGIN
DELETE #rash
WHERE RIGHT(RTRIM(CODE),3) IN ('000') AND LEFT(code,7) NOT IN ('0009600', '0007900')
END

END

---------------------------------------------
/*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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,14) + '000000', '', max(Col2),max(Col3), max(Col4), '000',sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), left(Col14,14) + '000000'
	from #rash
	where col5 <> '000'
	group by left(Code,14) + '000000', left(Col14,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,7) + '0000000000000', '', max(Col2),max(Col3), '0000000', '000', sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), left(col14,7) + '0000000000000'
	from #rash
	where col5 <> '000'
	group by left(Code,7) + '0000000000000', left(col14,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,5) + '000000000000000', '', max(Col2),left(col3,2) + '00', '0000000', '000', sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), left(col14,5) + '000000000000000'
	from #rash
	where col5 <> '000'
	group by left(Code,5) + '000000000000000', left(Col14,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,3) + '00000000000000000', '', max(Col2),'000', '0000000', '000', sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13),  left(col14,3) + '00000000000000000'
	from #rash
	where  col5 <> '000'
	group by left(Code,3) + '00000000000000000', left(Col14,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,12) + '00000000', '', max(Col2),max(Col3), max(Col4), '000', sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), left(Col14,12) + '00000000'
	from #rash
	where  col5 <> '000'
	group by left(Code,12) + '00000000', left(Col14,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,10) + '0000000000', '', max(Col2),max(Col3), max(Col4), '000', sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), left(Col14,10) + '0000000000'
	from #rash
	where col5 <> '000'
	group by left(Code,10) + '0000000000', left(Col14,10) + '0000000000'
END

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)
SELECT 0,0,0,@LSF, 0, -1, 0, 0, '00096000000000000000', 'Расходы - всего', '', '', '', '', 0,0,0,0,0,0,0,0, '00096000000000000000'
WHERE NOT EXISTS(SELECT * FROM #rash WHERE code LIKE '%96000000000000%')

-- убираем целевые которых нет в справочнике
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
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)

/*Нужно выводить наименования расходов во всех стройчках*/
/*UPDATE #rash
SET COL1 = ''
WHERE  col5 <> '000'*/

if @iYear < 2011
exec ro_get_name_spr @iLT, 'COL5=SUBSTRING(CODE,15,3)=000#COL4=SUBSTRING(CODE,5,10)=0000000#COL3=SUBSTRING(CODE,1,4)=0000#RN_VIEW_KBK_ADM_M=LEFT(CODE,4)=000', '#rash', @varKScNameCode = 'CODE', @varKScNameName = 'COL1', @varKSiLSF = @LSF
else
exec ro_get_name_spr @iLT, 'COL5=SUBSTRING(CODE,15,3)=000#COL4=SUBSTRING(CODE,5,10)=0000000#COL3=SUBSTRING(CODE,1,4)=0000#R_SPR_ADM_2011=LEFT(CODE,4)=000', '#rash', @varKScNameCode = 'CODE', @varKScNameName = 'COL1', @varKSiLSF = @LSF
----------------------------------------------

--if @AtrInOnePage = 1 -- еще общий итог по администраторма
--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)
--	select 0, 0, 0, max(link_saved_form), 0, -1, 0, 0, '00096000000000000000', 'Расходы - всего', max(Col2),'000', '9600000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), '00096000000000000000'
--	from #rash
--	where col6 = '000' and col5 <> '000'
--end

select * from #rash order by left(code, 3), orders, Code

drop table #rash_itog
drop table #rash
-------------------------------------------------------------------------------------------------

-- таблица источники
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(1000), Col2 varchar(1000), Col3 varchar(1000), Col4 float, Col5 float, Col6 float, Col7 float, Col8 float, Col9 float, Col10 varchar(50))

insert #ist exec dbo.rn_get_all_adm_table 	@LSF, 3, @bDeleteEmptyRows, @AtrInOnePage, 1

-- добавляем обязательные кода:
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)
select 0, 0, 0, 0, 0, -2, 0, 0, '00050090000000000000000', 'Источники финансирования дефицита бюджета - всего', '500', '90000000000000000', 0,0,0,0,0,0,'00050090000000000000000'
where not exists (select top 1 * from #ist where code =  '00050090000000000000000')

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)
select 0, 0, 0, 0, 0, -1, 0, 0, '00052001000000000000000', 'источники внутреннего финансирования бюджета', '520', '01000000000000000', 0,0,0,0,0,0,'00052001000000000000000'
where not exists (select top 1 * from #ist where code =  '00052001000000000000000')

update #ist
set orders = 2
where col2 = '620'

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)
select 0, 0, 0, 0, 0, 1, 0, 0, '00062002000000000000000', 'источники внешнего финансирования бюджета', '620', '02000000000000000', 0,0,0,0,0,0,'00062002000000000000000'
where not exists (select top 1 * from #ist where code =  '00062002000000000000000')

update #ist
set orders = 3
where col2 like '7%'

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)
select 0, 0, 0, 0, 0, 3, 0, 0, CASE WHEN @AtrInOnePage = 1 THEN '000' ELSE RTRIM(@vcAtr) END  + '70001050000000000000', 'Изменение остатков средств', '700', '', 0,0,0,0,0,0,'00070001050000000000000'
where not exists (select top 1 * from #ist where substring(code,4, 20) =  '70001050000000000000')

update #ist
set orders = 5
where col2 = '710'

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)
select 0, 0, 0, 0, 0, 4, 0, 0, CASE WHEN @AtrInOnePage = 1 THEN '000' ELSE RTRIM(@vcAtr) END  + '71001050000000000500', 'увеличение остатков средств, всего', '710', '', 0,0,0,0,0,0,'00071001050000000000500'
where not exists (select top 1 * from #ist where substring(code,4, 20) =  '71001050000000000500')

update #ist
set orders = 7
where col2 = '720'

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)
select 0, 0, 0, 0, 0, 6, 0, 0, CASE WHEN @AtrInOnePage = 1 THEN '000' ELSE RTRIM(@vcAtr) END  + '72001050000000000600', 'уменьшение остатков средств, всего', '720', '', 0,0,0,0,0,0,'00072001050000000000600'
where not exists (select top 1 * from #ist where substring(code,4, 20) =  '72001050000000000600')

update #ist
set orders = 8
where col2 like '8%'

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00080004000000000000000', 'Изменение остатков по расчетам (стр.810 + 820)', '800', '04000000000000000', 0,0,0,0,0,0,'00080004000000000000000'
where not exists (select top 1 * from #ist where code =  '00080004000000000000000')

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00081005000000000000000', 'изменение остатков по расчетам с органами, организующими исполнение бюджета (стр.811 + 812)', '810', '05000000000000000', 0,0,0,0,0,0,'00081005000000000000000'
where not exists (select top 1 * from #ist where code =  '00081005000000000000000')

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00081106000000000000000', 'увеличение счетов расчетов (дебетовый остаток счета 121002000)', '811', '06000000000000000', 0,0,0,0,0,0,'00081106000000000000000'
where not exists (select top 1 * from #ist where code =  '00081106000000000000000')

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00081207000000000000000', 'уменьшение счетов расчетов (кредитовый остаток счета 130405000)', '812', '07000000000000000', 0,0,0,0,0,0,'00081207000000000000000'
where not exists (select top 1 * from #ist where code =  '00081207000000000000000')

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00082008000000000000000', 'Изменение остатков по внутренним расчетам (стр.821 + стр. 822)', '820', '08000000000000000', 0,0,0,0,0,0,'00082008000000000000000'
where not exists (select top 1 * from #ist where code =  '00082008000000000000000')

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00082109000000000000000', 'увеличение остатков по внутренним расчетам', '821', '09000000000000000', 0,0,0,0,0,0,'0082109000000000000000'
where not exists (select top 1 * from #ist where code =  '00082109000000000000000')

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)
select 0, 0, 0, 0, 0, 8, 0, 0, '00082201000000000000000', 'уменьшение остатков по внутренним расчетам', '822', '01000000000000000', 0,0,0,0,0,0,'00082201000000000000000'
where not exists (select top 1 * from #ist where code =  '00082201000000000000000')

select * from #ist order by orders, col2, code

drop table #ist

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.[RO_PRINT_127_ITOG_16] TO PUBLIC

GO




GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (фев  5 2016 11:42:02:290AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503164M (Отчет об исполнении бюджета)
-- Дата ввода : 20160101
-- Дата окончания действия :
-- Версия : 2016-02-05 11:42:02.287
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0503164M' AND [START_DATE] = '20160101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2016-02-05 11:42:02.287',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0503164M',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0503164M'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20160101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SMETA'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Отчет об исполнении бюджета',@vcNEW_FORM_CODE,@dNEW_START_DATE,4,1,1,1,18186,'RA_EXPORT_FORM_STANDART',0,1,'19000101',NULL,'191н'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'svodprint_page_one()','sv_0503164m_20150101.bas','','KirRepMakerMultiSheet.xls','SV_0503164M_20150101.XLT','',NULL,'RA_EXPORT_FORM_STANDART',0,'''$ADM$|''+LEFT(COL1,3) + ''|'' + SUBSTRING(COL1,4,5) + ''|'' + SUBSTRING(COL1,9,2)+''|0000|000|'' + RTRIM(COL2) + ''|'' +STR(COL3)+''|''+STR(COL4)+''|''+STR(COL5)+''|''+STR(COL6)+''|''+str(COL7)+''|''+dbo.RO_EXP(COL8)+''|''+dbo.RO_EXP(COL9)+''|''#
''$ADM$|''+LEFT(COL11,4)+''|''+SUBSTRING(COL11,5,7)+''|000|000|'' + RTRIM(COL3) + ''|'' +STR(COL4)+''|''+STR(COL5)+''|''+STR(COL6)+''|''+STR(COL7)+''|''+STR(COL8)+''|''+dbo.RO_EXP(COL9)+''|''+dbo.RO_EXP(COL10)+''|''#
 ''$ADM$|''+SUBSTRING(COL10,4,4) + ''|'' + SUBSTRING(COL10,8,4) + ''|'' + SUBSTRING(COL10,12,2) + ''|'' + SUBSTRING(COL10,14,4)+''|000|'' + LEFT(COL10,3) + ''|'' +STR(COL3)+''|''+STR(COL4)+''|''+STR(COL5)+''|''+STR(COL6)+''|''+str(COL7)+''|''+dbo.RO_EXP(COL8)+''|''+dbo.RO_EXP(COL9)+''|''
','C2 + C3 + C4+''|''+ C7 + ''|''+C8+''|''+C9+''|''+C10+''|''+C11+''|''+C12+''|''+C13+''|''+C14 # C2+C3+''|''+C6+''|''+C7+''|''+C8+''|''+C9+''|''+C10+''|''+C11+''|''+C12+''|''+C13 # 
C7+C2 + C3+ C4+C5+C6+''|''+C8+''|''+C9+''|''+C10+''|''+C11+''|''+C12+''|''+C13+''|''+C14',NULL,'264       ','REPORTS_ATR_ADM,REPORTS_ATR_PERCENT',NULL,NULL,'ro_print_164g|SV_0503164M_20111403.XLT',0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Доходы', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Код дохода по КД',@iLINK_TABLE,1,1,1,0,0,1,'R_SPR_DOH_17_2011','COL1,COL2','CODE,CODE_STR','NNNNNNNNNNNNNNNNN',NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утвержденные бюджетные назначения(прогнозные показатели)',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Доведенные бюджетные данные',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Исполнено',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Процент исполнения, %',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Не исполнено сумма, руб.(гр.4 - гр. 3)',@iLINK_TABLE,1,0,7,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Причины отклонений от планового процента исполнений - код',@iLINK_TABLE,1,1,8,0,10,1,'R_SPR_REASON_164','COL8,COL9','CODE,NAME',NULL,NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Причины отклонений от планового процента исполнений - пояснения',@iLINK_TABLE,1,1,9,0,2000,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Доходы', @iLINK_FORM,1, @iLINK_CODE_COL,1,'CALC_SKELET=sql.call("dbo.RO_CALC_SKELET",m.cAlias,0x0,''0503164G'',1,''20110101'')
','-1#LEFT(CODE,3)=''850''',0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Расходы', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'РзПр',@iLINK_TABLE,0,1,0,0,4,1,'R_SPR_RZPR_2011','COL1,COL3','CODE,CODE_STR','NNNN',NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'ЦСР',@iLINK_TABLE,0,1,0,0,10,1,'R_SPR_CSR_2016','COL2','CODE',NULL,NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Код строки',@iLINK_TABLE,1,1,2,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Утвержденные бюджетные назначения(прогнозные показатели)',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Доведенные бюджетные данные',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Исполнено',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Процент исполнения, %',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,NULL,2,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Не исполнено. сумма, руб.(гр.4 - гр. 3)',@iLINK_TABLE,1,0,7,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Отклонение показателя исполнения от планового показателя.- код',@iLINK_TABLE,1,1,8,0,10,1,'R_SPR_REASON_164','COL9,COL10','CODE,NAME',NULL,NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Отклонение показателя исполнения от планового показателя. причины откл',@iLINK_TABLE,1,1,9,0,2000,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Код расхода',@iLINK_TABLE,1,1,1,0,17,1,'R_SPR_AUTO_164_2016','COL3,COL11','CODE_STR,CODE',NULL,1,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Расходы', @iLINK_FORM,2, @iLINK_CODE_COL,1,'CALC_SKELET=sql.call("dbo.RO_CALC_SKELET",m.cAlias,0x0,''0503164M'',2,''20160101'')
KEY_FOX=PADR(RTRIM(COL1),4,''0'')+PADR(RTRIM(COL2),10,''0'')
KEY_WEB=LEFT(RTRIM(ISNULL(COL1,''''))+''0000'',4)+LEFT(RTRIM(isnull(COL2,''''))+''0000000000'',10)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,4)#COL2=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',5,10)
AUTOFILL_MASK=XXXXXXXXXXXXXXdddddd
AUTO_SPR_FORM=R_SPR_AUTO_164_2016 
AUTO_SPR_закоментировалCHECK=1#SUBSTRING(T.code,1,4)|2#SUBSTRING(T.code,5,10)
AUTO_SPR_CODE_STR=case when left(T.code,4) <> ''7900'' then ''200'' else ''450'' end
','-1#LEFT(CODE,3)=''960''
1#LEFT(CODE,3)=''790''',0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Источники', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Код источника финансирования',@iLINK_TABLE,0,1,1,0,17,1,'R_SPR_IST_17_2011_164','COL1,COL2','CODE_IST,CODE_STR',NULL,NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,0,1,2,0,3,1,NULL,NULL,NULL,'NNN',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утвержденные бюджетные назначения(прогнозные показатели)',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Доведенные бюджетные данные',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Исполнено',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Процент исполнения, %',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Не исполнено. сумма, руб.(гр.4 - гр. 3)',@iLINK_TABLE,1,0,7,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Отклонение показателя исполнения от планового показателя.- код',@iLINK_TABLE,1,1,8,0,10,1,'R_SPR_REASON_164','COL8,COL9','CODE,NAME',NULL,NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Отклонение показателя исполнения от планового показателя. причины откл',@iLINK_TABLE,1,1,9,0,2000,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Источники',@iLINK_TABLE,1,1,1,0,0,1,'R_SPR_IST_17_2011_164','COL10','CODE',NULL,1,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Источники', @iLINK_FORM,3, @iLINK_CODE_COL,1,'CALC_SKELET=sql.call("dbo.RO_CALC_SKELET",m.cAlias,0x0,''0503164G'',3,''20110101'')
KEY_FOX=PADR(RTRIM(COL2),3,''0'')+PADR(RTRIM(COL1),17,''0'')
KEY_WEB=LEFT(RTRIM(ISNULL(COL2,''''))+''000'',3)+LEFT(RTRIM(isnull(COL1,''''))+''000000000000000000'',17)
SPLIT=COL1=SUBSTRING(CODE_ROW,4,17)#COL2=SUBSTRING(CODE_ROW,1,3)
','-1#LEFT(CODE,6)=''500900''',0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'Проверка на пустые строки =  0',0,0,0,'20130118','','','','0503164M','20160101','Екатеринбург','=',9,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'Проверка на пустые строки =  0',0,0,0,'20130118','','','','0503164M','20160101','Екатеринбург','=',9,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'Проверка на пустые строки =  0',0,0,0,'20130118','','','','0503164M','20160101','Екатеринбург','=',9,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 3
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,2,'+',NULL,NULL,NULL,NULL,0,0,'RN_CHECK_EMPTY_STRING(7, 1, ''A.CODE_ROW <>"8500000000"'')','Проверка на пустые строки','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,2,'+',NULL,NULL,NULL,NULL,0,0,'RN_CHECK_EMPTY_STRING(8, 2,  ''A.CODE_ROW <>"96000000000" AND A.CODE_ROW <>"79000000000"'')','Проверка на пустые строки','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,2,'+',NULL,NULL,NULL,NULL,0,0,'RN_CHECK_EMPTY_STRING(7, 3, ''A.CODE_ROW <>"50090000000000000000"'')','Проверка на пустые строки','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 6
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '2         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'2','Месячные формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '3         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'3','Квартальные формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '999999    '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'999999','формы отчетности',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2016-02-05 11:42:02.287',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 = '2016-02-05 11:42:02.287'
	BEGIN
		SELECT @vcMessage = 'Форма 0503164M с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503164M с версией от ' + @vcMessage + ' не может быть обновлена версией от 2016-02-05 11:42:02.287. Обновление отклонено.'
	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

------------------- ВЫГРУЗКА СПРАВОЧНИКА: Автозаолняемый справочник для формы 0503164 С КОДОМ R_SPR_AUTO_164_2016------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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 ('Code_str', 2, 'Code_str', 'Код строки', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 3, 'isnull(Long_Name,Name)', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('PROPERTY', 4, 'PROPERTY', 'Итог', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_AUTO_164_2016'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_AUTO_164_2016', 'Автозаолняемый справочник для формы 0503164', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Автозаолняемый справочник для формы 0503164 (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_AUTO_164_2016]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Code_str as [CODE_STR],PROPERTY as [PROPERTY],max(isnull(Long_Name,Name)) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_AUTO_164_2016' GROUP BY Code,Code_str,PROPERTY, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_AUTO_164_2016] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_AUTO_164_2016')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_AUTO_164_2016'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_164_2016', 'Автозаолняемый справочник для формы 0503164', 229, (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_AUTO_164_2016', NAME = 'Автозаолняемый справочник для формы 0503164', ORDERS = '229', 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_AUTO_164_2016'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_164_2016_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_164_2016_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_164_2016_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_164_2016_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_164_2016_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_164_2016_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_164_2016_Code_str', 'Код строки', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_164_2016_Code_str', NAME = 'Код строки', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_164_2016_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_164_2016_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_164_2016_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_164_2016_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016_PROPERTY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_164_2016_PROPERTY', 'Итог', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_164_2016_PROPERTY', NAME = 'Итог', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_164_2016'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_164_2016_PROPERTY'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016', 'TITLE', 'Автозаолняемый справочник для формы 0503164'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_AUTO_164_2016'')'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_AUTO_164_2016'')'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016', 'SERVER_TABLE_NAME', 'R_SPR_AUTO_164_2016'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_AUTO_164_2016'''
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_Code_str', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_PROPERTY', 'TITLE', 'Итог'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_PROPERTY', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_PROPERTY', 'CONTROLSOURCE', 'm.cAlias + ".PROPERTY"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_164_2016_PROPERTY', 'FIELD_DATA', 'PROPERTY'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_164_2016', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_164_2016', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_164_2016', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_164_2016', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_AUTO_164_2016',0,'Автозаолняемый справочник для формы 0503164','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_AUTO_164_2016',@link_self,'Автозаолняемый справочник для формы 0503164','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_AUTO_164_2016')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_AUTO_164_2016')
delete report_kbk where code_form= 'R_SPR_AUTO_164_2016'
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 '01011234567000',0,'R_SPR_AUTO_164_2016',1,'',0,'200',0,'','', '19000101','30000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '79000000000000',0,'R_SPR_AUTO_164_2016',1,'',0,'450',0,'','', '19000101','30000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '96000000000000',0,'R_SPR_AUTO_164_2016',1,'',0,'200',0,'','', '19000101','30000101',0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_AUTO_164_2016'

GO

-- Сгенерировано х.п. RA_EXPORT_GROUP_KS. (фев  5 2016  4:22:45:547PM)
-- Выгружены следующие группы междокументных КС:
-- 2016_5 - Заполнение: 0503164M - 0503127M (16 шт.)
-- Параметры выгрузки:
-- удаление старых КС : да

SET NOCOUNT               ON
SET ANSI_NULLS            ON
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

----------------------------------------------------------------------------------------------------
-- Раздел удаления правил.

DELETE
FROM dbo.[REPORT_CONTROL_RULES]
WHERE [LINK_RULE] IN (SELECT [A].[LINK_RULE]
                      FROM dbo.[REPORT_CONTROL_GROUP] [A]
                      JOIN dbo.[REPORT_GROUP_KS]      [B] ON [A].[LINK_GROUP_KS] = [B].[LINK_GROUP_KS]
                      WHERE [B].[CODE] = '2016_5' AND
                            (SELECT COUNT(*)
                             FROM dbo.[REPORT_CONTROL_GROUP] [C]
                             WHERE [C].[LINK_RULE] = [A].[LINK_RULE]) = 1)

DELETE [B]
FROM dbo.[REPORT_GROUP_KS]      [A]
JOIN dbo.[REPORT_CONTROL_GROUP] [B] ON [A].[LINK_GROUP_KS] = [B].[LINK_GROUP_KS]
WHERE [A].[CODE] = '2016_5'

GO

----------------------------------------------------------------------------------------------------
-- Раздел сохранения правил.
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#tabRULES') IS NOT NULL
BEGIN
   DROP TABLE #tabRULES
END

CREATE TABLE #tabRULES ([LINK_RULE]       INT NULL,
                        [LINK_TASK]       INT NULL,
                        [IsOutside]       TINYINT NULL,
                        [LINK_FORM]       INT NULL,
                        [OrderRule]       INT NULL,
                        [PERIOD]          SMALLINT NULL,
                        [PERIOD_NOM]      SMALLINT NULL,
                        [ORG_LEVEL]       SMALLINT NULL,
                        [IsSvod]          SMALLINT NULL,
                        [STR_RULE]        VARCHAR (6000) NULL,
                        [IsDoschet]       TINYINT NULL,
                        [CALC_ORDERS]     INT NULL,
                        [IsSystemsRule]   TINYINT NULL ,
                        [MODIFY_DATE]     DATETIME NULL,
                        [ROWS]            VARCHAR(1000),
                        [COLS]            VARCHAR(250),
                        [ROWS_DESC]       VARCHAR (250),
                        [CODE_FORM]       VARCHAR (250),
                        [START_DATE_FORM] VARCHAR (250),
                        [REGION]			 VARCHAR (100),
                        [SIGN_SR]         CHAR(2)      NOT NULL,
                        [ALGORITHM]       TINYINT      NOT NULL,
                        [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                        [COMMENT]     VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabRULES',@iERROR)
END

GO

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (1,1,568291,7,0,0,0,'ф.0503164Mт.3стр.52001000000000000000гр.3 =  ф.0503127Mт.3стр.52001000000000000000гр.4',1,4,0,'20160201','','','','',NULL,'ks                                                                                                  ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (2,1,568292,7,0,0,0,'ф.0503164Mт.3стр.52001000000000000000гр.5 =  ф.0503127Mт.3стр.52001000000000000000гр.8',1,4,0,'20160201','','','','',NULL,'ks                                                                                                  ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (3,1,568293,7,0,0,0,'ф.0503164Mт.3стр.62002000000000000000гр.5 =  ф.0503127Mт.3стр.62002000000000000000гр.8',1,4,0,'20160201','','','','',NULL,'ks                                                                                                  ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (4,1,568294,7,0,0,0,'ф.0503164Mт.3стр.62002000000000000000гр.3 =  ф.0503127Mт.3стр.62002000000000000000гр.4',1,4,0,'20160201','','','','',NULL,'ks                                                                                                  ','=',1,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (5,1,568295,7,0,0,0,'ф.0503164Mт.1гр.3 =  ф.0503127Mт.1гр.4',1,2,1,'20160201','','','','',NULL,'                                                                                                    ','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (6,1,568296,7,0,0,0,'ф.0503164Mт.1гр.5 =  ф.0503127Mт.1гр.8',1,2,1,'20160201','','','','',NULL,'                                                                                                    ','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (7,1,568297,7,0,0,0,'ф.0503164Mт.2гр.3 =  ф.0503127Mт.2гр.6',1,2,1,'20160205','','','','',NULL,'                                                                                                    ','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (8,1,568298,7,0,0,0,'ф.0503164Mт.2гр.5 =  ф.0503127Mт.2гр.10',1,2,1,'20160205','','','','',NULL,'                                                                                                    ','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (9,1,568299,7,0,0,0,'ф.0503164Mт.3гр.3 =  ф.0503127Mт.3гр.4',1,2,1,'20160201','','','','',NULL,'                                                                                                    ','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (10,1,568300,7,0,0,0,'ф.0503164Mт.3гр.5 =  ф.0503127Mт.3гр.8',1,2,1,'20160201','','','','',NULL,'                                                                                                    ','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (11,1,568301,7,0,0,0,'ф.0503164Mт.2гр.3 =  ф.0503164Mт.2гр.3',1,3,1,'20160201','','','','',NULL,'                                                                                                    ','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (12,1,568302,7,0,0,0,'ф.0503164Mт.2гр.4 =  ф.0503164Mт.2гр.4',1,3,1,'20160201','','','','',NULL,'                                                                                                    ','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (13,1,568303,7,0,0,0,'ф.0503164Mт.1гр.3 =  ф.0503164Mт.1гр.3',1,3,1,'20160201','','','','',NULL,'                                                                                                    ','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (14,1,568304,7,0,0,0,'ф.0503164Mт.1гр.4 =  ф.0503164Mт.1гр.4',1,3,1,'20160201','','','','',NULL,'                                                                                                    ','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (15,1,568305,7,0,0,0,'ф.0503164Mт.3гр.3 =  ф.0503164Mт.3гр.3',1,3,1,'20160201','','','','',NULL,'                                                                                                    ','=',0,'','')

INSERT #tabRULES ([LINK_RULE],[IsOutside],[OrderRule],[PERIOD],[PERIOD_NOM],[ORG_LEVEL],[IsSvod],[STR_RULE],[IsDoschet],[CALC_ORDERS],[IsSystemsRule],[MODIFY_DATE],[ROWS],[COLS],[ROWS_DESC],[CODE_FORM],[START_DATE_FORM],[REGION],[SIGN_SR],[ALGORITHM],[ATR_CODE_SR],[COMMENT])
VALUES (16,1,568306,7,0,0,0,'ф.0503164Mт.3гр.4 =  ф.0503164Mт.3гр.4',1,3,1,'20160201','','','','',NULL,'                                                                                                    ','=',0,'','')


GO

DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #tabRules) <> 16
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #tabRules',0)
END

GO

DECLARE @iERROR INT
IF OBJECT_ID('tempdb..#tabROWS') IS NOT NULL
BEGIN
   DROP TABLE #tabROWS
END

CREATE TABLE #tabROWS ([LINK_RULE]       INT NULL,
                       [OrderRow]        INT NULL,
                       [VAL_TYPE]        TINYINT NULL,
                       [SIGN]            CHAR(2) NULL,
                       [LINK_FORM]       INT NULL,
                       [LINK_TABLE]      INT NULL,
                       [LINK_COL]        INT NULL,
                       [LINK_ROW]        INT NULL,
                       [PERIOD_FORM]     SMALLINT NULL,
                       [FACTOR]          FLOAT NULL,
                       [EXEC_PROC]       VARCHAR(250) NULL,
                       [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                       [CODE_ROW]        VARCHAR(250) NULL,
                       [FILTER]          VARCHAR(1000) NULL,
                       [FILTER_DESC]     VARCHAR(250) NULL,
                       [MASKA]           VARCHAR(250) NULL,
                       [MASKA_DESC]      VARCHAR(250) NULL,
                       [PERIOD_TYPE]     TINYINT,
                       [BUDG_CODE]       CHAR(5),
                       [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                       [COL]             VARCHAR(100) NULL,
                       [ROW]             VARCHAR(100) NULL,
                       [TABLE]           VARCHAR(25)  NULL,
                       [START_DATE_FORM] DATETIME     NULL,
                       [PERIOD_YEAR]     SMALLINT     NULL,
                       [ATR_CODE]        VARCHAR(254) NOT NULL,
                       [PART]            TINYINT      NOT NULL,
                       [BEGIN_DATE]      DATETIME     NULL,
                       [PX]              FLOAT(53)    NOT NULL,
                       [PX_COMMENT]      VARCHAR(600) NOT NULL,
                       [PROPERTY]        TINYINT      DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabROWS',@iERROR)
END

GO

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (5,2,4,'+ ',0,0,'','','','((substring(code,11,4)<>''0000''  or (substring(code,11,4)=''0000'' and not exists(select top 1 * from #report_dinamics RD1 where RD1.Link_SF = A.LSF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and RD1.Link_Table = RD.Link_Table and substring(RD1.Code_Row,11,4) <> ''0000'') and code not in (select CD from dbo.RO_SELECT_FORM_TOTALS_DOH_17(0,$ОТЧЕТ$,1) where link_table=$ТАБЛИЦА$)))  and isnull(COL(4),0)<>0) OR SUBSTRING(CODE,1,8)=''85000000''','','CODE','',8,'     ','4','','1','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (6,2,4,'+ ',0,0,'','','','((substring(code,11,4)<>''0000''  or (substring(code,11,4)=''0000'' and not exists(select top 1 * from #report_dinamics RD1 where RD1.Link_SF = A.LSF and LEFT(RD1.Code_Row,10) = LEFT(CODE,10) and RD1.Link_Table = RD.Link_Table and substring(RD1.Code_Row,11,4) <> ''0000'') and code not in (select CD from dbo.RO_SELECT_FORM_TOTALS_DOH_17(0,$ОТЧЕТ$,1) where link_table=$ТАБЛИЦА$)))  and isnull(COL(4),0)<>0) OR SUBSTRING(CODE,1,8)=''85000000''','','CODE','',8,'     ','8','','1','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (7,2,4,'+ ',0,0,'','','','(right(rtrim(code),3) not in (''200'',''000'',''210'',''220'',''230'',''240'',''250'',''260'',''300'',''500'',''600'' )and isnull(COL(4),0)<>0) OR (SUBSTRING(CODE,1,11) in (''96000000000'', ''79000000000''))','','LEFT(CODE,14)+''000000''','',8,'     ','8','','2','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (8,2,4,'+ ',0,0,'','','','(right(rtrim(code),3) not in (''200'',''000'',''210'',''220'',''230'',''240'',''250'',''260'',''300'',''500'',''600'' )and isnull(COL(4),0)<>0) OR (SUBSTRING(CODE,1,11) in (''96000000000'', ''79000000000''))','','LEFT(CODE,14)+''000000''','',8,'     ','12','','2','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (1,2,3,'+ ',0,0,'','','52001000000000000000','','','','',8,'     ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (2,2,3,'+ ',0,0,'','','52001000000000000000','','','','',8,'     ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (3,2,3,'+ ',0,0,'','','62002000000000000000','','','','',8,'     ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (4,2,3,'+ ',0,0,'','','62002000000000000000','','','','',8,'     ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (10,2,4,'+ ',0,0,'','','','(code not in (select CD from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,$ОТЧЕТ$,1) where link_table=$ТАБЛИЦА$) and isnull(COL(4),0)<>0  and COL(2) not in (''700'',''720'',''710''))  or code=''50090000000000000000''','','CODE','',8,'     ','8','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (9,2,4,'+ ',0,0,'','','','(code not in (select CD from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,$ОТЧЕТ$,1) where link_table=$ТАБЛИЦА$) and isnull(COL(4),0)<>0  and COL(2) not in (''700'',''720'',''710''))  or code=''50090000000000000000''','','CODE','',8,'     ','4','','3','0503127M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (13,1,4,'+ ',0,0,'','','','(isnull(COL(3),0) = isnull(COL(4),0))and substring(code,1,3)<>''850''','','CODE','',8,'     ','3','','1','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (13,2,4,'+ ',0,0,'','','','(isnull(COL(3),0) = isnull(COL(4),0))and substring(code,1,3)<>''850''','','CODE','',8,'     ','3','','1','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (14,1,4,'+ ',0,0,'','','','(isnull(COL(3),0) = isnull(COL(4),0))and substring(code,1,3)<>''850''','','CODE','',8,'     ','4','','1','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (14,2,4,'+ ',0,0,'','','','(isnull(COL(3),0) = isnull(COL(4),0))and substring(code,1,3)<>''850''','','CODE','',8,'     ','4','','1','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (5,1,4,'+ ',0,0,'','','','','','CODE','',8,'     ','3','','1','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (6,1,4,'+ ',0,0,'','','','','','CODE','',8,'     ','5','','1','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (7,1,4,'+ ',0,0,'','','','','','LEFT(CODE,11)+''000000''','',8,'     ','4','','2','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (8,1,4,'+ ',0,0,'','','','','','LEFT(CODE,11)+''000000''','',8,'     ','6','','2','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (11,1,4,'+ ',0,0,'','','','substring(code,1,4) not in (''9600'',''7900'') and abs(isnull(COL(5),0)-isnull(COL(4),0)) = 0','','CODE','',8,'     ','4','','2','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (11,2,4,'+ ',0,0,'','','','substring(code,1,4) not in (''9600'',''7900'') and abs(isnull(COL(5),0)-isnull(COL(4),0)) = 0','','CODE','',8,'     ','4','','2','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (12,1,4,'+ ',0,0,'','','','substring(code,1,4) not in (''9600'',''7900'') and abs(isnull(COL(5),0)-isnull(COL(4),0)) = 0','','CODE','',8,'     ','5','','2','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (12,2,4,'+ ',0,0,'','','','substring(code,1,4) not in (''9600'',''7900'') and abs(isnull(COL(5),0)-isnull(COL(4),0)) =0','','CODE','',8,'     ','5','','2','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (10,1,4,'+ ',0,0,'','','','','','CODE','',8,'     ','5','','3','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (1,1,3,'+ ',0,0,'','','52001000000000000000','','','','',8,'     ','3','','3','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (15,1,4,'+ ',0,0,'','','','(isnull(COL(3),0) = isnull(COL(4),0))and code not in (''50090000000000000000'')','','CODE','',8,'     ','3','','3','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (15,2,4,'+ ',0,0,'','','','(isnull(COL(3),0) = isnull(COL(4),0))and code not in (''50090000000000000000'')','','CODE','',8,'     ','3','','3','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (16,1,4,'+ ',0,0,'','','','(isnull(COL(3),0) = isnull(COL(4),0))and code not in (''50090000000000000000'')','','CODE','',8,'     ','4','','3','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (16,2,4,'+ ',0,0,'','','','(isnull(COL(3),0) = isnull(COL(4),0))and code not in (''50090000000000000000'')','','CODE','',8,'     ','4','','3','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',1,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (9,1,4,'+ ',0,0,'','','','','','CODE','',8,'     ','3','','3','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (4,1,3,'+ ',0,0,'','','62002000000000000000','','','','',8,'     ','3','','3','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (3,1,3,'+ ',0,0,'','','62002000000000000000','','','','',8,'     ','5','','3','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)

INSERT #tabROWS ([LINK_RULE],[OrderRow],[VAL_TYPE],[SIGN],[PERIOD_FORM],[FACTOR],[EXEC_PROC],[EXEC_PROC_DESC],[CODE_ROW],[FILTER],[FILTER_DESC],[MASKA],[MASKA_DESC],[PERIOD_TYPE],[BUDG_CODE],[COL],[ROW],[TABLE],[CODE_FORM_ROW],[START_DATE_FORM],[PERIOD_YEAR],[ATR_CODE],[PART],[BEGIN_DATE],[PX],[PX_COMMENT],[PROPERTY])
VALUES (2,1,3,'+ ',0,0,'','','52001000000000000000','','','','',8,'     ','5','','3','0503164M            ','20160101',NULL,'REPORTS_ATR_ADM',0,NULL,1,'',0)


GO

DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #tabRows) <> 32
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #tabRows',0)
END

GO

DECLARE @iERROR INT
IF OBJECT_ID('tempdb..#tabGroupRules') IS NOT NULL
BEGIN
   DROP TABLE #tabGroupRules
END

CREATE TABLE #tabGroupRules ([GROUP_CODE] VARCHAR(20) NOT NULL,
                             [LINK_RULE]  INT         NOT NULL)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabGroupRules',@iERROR)
END

GO
INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (1,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (2,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (3,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (4,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (5,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (6,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (7,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (8,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (9,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (10,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (11,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (12,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (13,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (14,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (15,'2016_5')

INSERT #tabGroupRules ([LINK_RULE],[GROUP_CODE])
VALUES (16,'2016_5')


GO

DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #tabGroupRules) <> 16
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #tabGroupRules',0)
END

GO

----------------------------------------------------------------------------------------------------
-- Раздел сохранения групп.
DECLARE @vcGROUP_CODE CHAR(20), @iGROUP_LINK INT, @iLINK_RULE INT

SELECT @iGROUP_LINK = [LINK] FROM dbo.[RA_VIEW_GROUP_KS] WHERE [CODE] = '2016_5'
EXEC dbo.[RA_SAVE_GROUP_KS] @iGROUP_LINK OUTPUT, '2016_5' , 'Заполнение: 0503164M - 0503127M', 2, 0, '20160101', NULL

GO

DECLARE @iERROR INT

CREATE INDEX #IX_tabROWS ON #tabROWS([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #tabRULES([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#tabRULES', '#tabROWS', 1, '#tabGroupRules'
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog

COMMIT TRANSACTION -- Фиксация транзакции.
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
/****** Объект: Имущественные налоговые вычеты******/

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 @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.90, 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, 5.1, 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, 22, 22, 22, 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, 10, 10, 10, 3
GO


GO
UPDATE DBO.S_OBJECTS
SET CODE = 'COLUMN_NAME_VKR_CM_T', NAME = 'Источник для взносов', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
WHERE CODE ='COLUMN_NAME_VKR_CM_T'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_CM_T', 'TITLE', 'Источник для взносов'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_CM_T', 'COMMENTARY', 'Источник финансирования для взносов'
GO


/****** Объект: Источник начислений******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_VKR2_CM_T')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_NAME_VKR2_CM_T')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_NAME_VKR2_CM_T')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_NAME_VKR2_CM_T')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_VKR2_CM_T'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_VKR2_CM_T')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_VKR2_CM_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_VKR2_CM_T', 'Источник начислений', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_VKR2_CM_T', NAME = 'Источник начислений', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_VKR2_CM_T'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_CM_T', 'TITLE', 'Источник начислений'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_CM_T', 'ORDER_NUMBER', '2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_CM_T', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_SRC_FIN '', oForm.apageframe1.page1.bSPISOK.bGRID1.RecordSource, ''LINK, CODE'', ''LINK_VKR2,NAME_VKR2'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_CM_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_CM_T', 'CONTROLSOURCE', 'm.cAlias + ".NAME_VKR2"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_CM_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_CM_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_CM_T', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_CM_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_VKR2"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_CM_T', 'COMMENTARY', 'Источник из операций по начислению оплаты труда'
GO



GO
UPDATE DBO.S_OBJECTS
SET CODE = 'COLUMN_NAME_VKR_DGH_T3', NAME = 'Источник для взносов', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
WHERE CODE ='COLUMN_NAME_VKR_DGH_T3'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T3', 'TITLE', 'Источник для взносов'
GO


/****** Объект: Источник начислений******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_VKR2_DGH_T3')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_NAME_VKR2_DGH_T3')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_NAME_VKR2_DGH_T3')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_NAME_VKR2_DGH_T3')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_VKR2_DGH_T3'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_VKR2_DGH_T3')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_VKR2_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_VKR2_DGH_T3', 'Источник начислений', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_VKR2_DGH_T3', NAME = 'Источник начислений', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_VKR2_DGH_T3'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_DGH_T3', 'TITLE', 'Источник начислений'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_DGH_T3', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_SRC_FIN '', oForm.Apageframe1.Page3.BSpisok.BGrid1.RecordSource, ''LINK, CODE'', ''LINK_VKR2,NAME_VKR2'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_DGH_T3', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".NAME_VKR2"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_DGH_T3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_DGH_T3', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_VKR2"'
GO





GO
/****** Объект: Источник******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_VKR2_ESN_T1_G')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_NAME_VKR2_ESN_T1_G')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_NAME_VKR2_ESN_T1_G')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_NAME_VKR2_ESN_T1_G')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_VKR2_ESN_T1_G'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_VKR2_ESN_T1_G')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_VKR2_ESN_T1_G')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_VKR2_ESN_T1_G', 'Источник начислений', 32, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DEDUCT_ESN_TABLE1_G'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_VKR2_ESN_T1_G', NAME = 'Источник начислений', ORDERS = '32', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DEDUCT_ESN_TABLE1_G'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_VKR2_ESN_T1_G'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_ESN_T1_G', 'TITLE', 'Источник начислений'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_ESN_T1_G', 'ORDER_NUMBER', '2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_ESN_T1_G', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_SRC_FIN'', oForm.bSPISOK.bGRID1.RecordSource, ''LINK, CODE'', ''LINK_VKR2,NAME_VKR2'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_ESN_T1_G', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_ESN_T1_G', 'CONTROLSOURCE', 'm.cAlias + ".NAME_VKR2"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_ESN_T1_G', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_ESN_T1_G', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_ESN_T1_G', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_ESN_T1_G', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_VKR2"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR2_ESN_T1_G', 'COMMENTARY', 'Источник из операций по начислению оплаты труда'
GO



UPDATE DBO.S_OBJECTS
SET CODE = 'COLUMN_NAME_VKR_ESN_T1_G', NAME = 'Источник для взносов', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DEDUCT_ESN_TABLE1_G'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
WHERE CODE ='COLUMN_NAME_VKR_ESN_T1_G'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_ESN_T1_G', 'COMMENTARY', 'Источник финансирования для проводок по страховым взносам'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_ESN_T1_G', 'TITLE', 'Источник для взносов'
GO


GO
--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ
DECLARE @TD_LINK INT
SET @TD_LINK = (SELECT TOP 1 LINK FROM dbo.TYP_DAYS WHERE WORK_D = 1 AND (SYMB LIKE 'П%' OR NAME LIKE 'Пред%празн%'))
IF COALESCE(@TD_LINK,0) > 0
BEGIN
	UPDATE dbo.HOLIDAYS SET TD_LINK = @TD_LINK WHERE [DAY] = 20 AND [MONTH] = 2 AND [YEAR] = '2016'
	UPDATE dbo.HOLIDAYS SET TD_LINK = @TD_LINK WHERE [DAY] = 3 AND [MONTH] = 11 AND [YEAR] = '2016'
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 = 2
		WHILE @MONTH <= 12
		BEGIN

			IF 1=1--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
		
					DELETE FROM dbo.GRAPHIC_DAYS WHERE LINK_UP = @LINK2
		
					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
--RELATED_LIST_DOP_CLASSIF
UPDATE DBO.s_tables 
SET QUERY_ADD = 'left(''Строка таблицы лимитов\ассигнований по '' +    (case when vkr.code is not null then '' КБК '' +rtrim(convert(varchar(30),vkr.code)) else '''' end) +   (case when ekr.code is not null then '' ЕКР '' +rtrim(convert(varchar(3),ekr.code)) else '''' end) +   (case when dop_cl.code is not null then '' Доп. классиф. '' +rtrim(convert(varchar(2),dop_cl.code)) else '''' end) +   '', сумма '' + rtrim(convert(varchar(20),p1+p2+p3+p4+p5+p6+p7+p8+p9+p10+p11+p12)), 250) as str_warning,    T1.LINK_UP as exec_link,   ''FINANS_TABLE'' as exec_object'
WHERE NAME = 'FINANSE'
GO

exec dbo.U_UPDATE_SCRIPT_PROPERTY 'RELATED_LIST_DOP_CLASSIF', 1, 'NOSCRIPT'
GO

EXEC dbo.XI_CREATE_TEST_REC_FUNC 'DOP_CLASSIF'
GO

--RELATED_LIST_g_prov
exec dbo.U_UPDATE_SCRIPT_PROPERTY 'RELATED_LIST_g_prov', 1, 'NOSCRIPT'
GO

EXEC dbo.XI_CREATE_TEST_REC_FUNC 'g_prov'
GO

--RELATED_LIST_KOSGU
exec dbo.U_UPDATE_SCRIPT_PROPERTY 'RELATED_LIST_KOSGU', 1, 'NOSCRIPT'
GO

EXEC dbo.XI_CREATE_TEST_REC_FUNC 'KOSGU'
GO


--RELATED_LIST_BA_MOL
exec dbo.U_UPDATE_SCRIPT_PROPERTY 'RELATED_LIST_BA_MOL', 1, 'NOSCRIPT'
GO

EXEC dbo.XI_CREATE_TEST_REC_FUNC 'BA_MOL'
GO

--RELATED_LIST_DEPARTMENTS
exec dbo.U_UPDATE_SCRIPT_PROPERTY 'RELATED_LIST_DEPARTMENTS', 1, 'NOSCRIPT'
GO

EXEC dbo.XI_CREATE_TEST_REC_FUNC 'DEPARTMENTS'
GO

--RELATED_LIST_KL_KBK
exec dbo.U_UPDATE_SCRIPT_PROPERTY 'RELATED_LIST_KL_KBK', 1, 'NOSCRIPT'
GO

EXEC dbo.XI_CREATE_TEST_REC_FUNC 'KL_KBK'
GO

--RELATED_LIST_PA_DISH
exec dbo.U_UPDATE_SCRIPT_PROPERTY 'RELATED_LIST_PA_DISH', 1, 'NOSCRIPT'
GO

EXEC dbo.XI_CREATE_TEST_REC_FUNC 'PA_DISH'
GO

--RELATED_LIST_PA_MENU_DECOMPOSE
exec dbo.U_UPDATE_SCRIPT_PROPERTY 'RELATED_LIST_PA_MENU_DECOMPOSE', 1, 'NOSCRIPT'
GO

EXEC dbo.XI_CREATE_TEST_REC_FUNC 'PA_MENU_DECOMPOSE'
GO

--RELATED_LIST_PAYS
exec dbo.U_UPDATE_SCRIPT_PROPERTY 'RELATED_LIST_PAYS', 1, 'NOSCRIPT'
GO

EXEC dbo.XI_CREATE_TEST_REC_FUNC 'PAYS'
GO



GO
EXEC X_SET_PROP 'SAL_SFIN_NENVD', 'VISIBLE', '11'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KBK', 'VISIBLE', '11'
GO
EXEC X_SET_PROP 'SAL_SFIN_USER_ACC', 'VISIBLE', '11'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KAU', 'VISIBLE', '11'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KAU', 'VISIBLE', '11'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_DOP_KL', 'VISIBLE', '11'
GO
EXEC X_SET_PROP 'SAL_SFIN_ACC_ESN', 'VISIBLE', '11'
GO
EXEC X_SET_PROP 'SAL_SFIN_LACC', 'VISIBLE', '11'
GO
EXEC X_SET_PROP 'SAL_SFIN_N_USED', 'VISIBLE', '11'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_CODE', 'VISIBLE', '11'
GO

/****** Объект: Источник для начислений взносов и пособий******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SAL_SFIN_SS_CODE')
	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_SFIN_SS_CODE')
	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_SFIN_SS_CODE')
	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_SFIN_SS_CODE')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SAL_SFIN_SS_CODE'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SAL_SFIN_SS_CODE')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_SS_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_SS_CODE', 'Источник для начислений взносов и пособий', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_SS_CODE', NAME = 'Источник для начислений взносов и пособий', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_SS_CODE'
GO
EXEC X_SET_PROP 'SAL_SFIN_SS_CODE', 'TITLE', 'Источник для начислений взносов и пособий'
GO
EXEC X_SET_PROP 'SAL_SFIN_SS_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_SRC_FIN'', oForm.ALIAS, ''LINK, CODE'', ''LINK_SS_SFIN,SSF_CODE'', '''', '''', ''USED=1'', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'SAL_SFIN_SS_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SAL_SFIN_SS_CODE', 'CONTROLSOURCE', 'm.cAlias + ".SSF_CODE"'
GO
EXEC X_SET_PROP 'SAL_SFIN_SS_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_SS_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SAL_SFIN_SS_CODE', 'SHORT_CODE_OBJ', 'SS_CODE'
GO
EXEC X_SET_PROP 'SAL_SFIN_SS_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SSF_CODE"'
GO
EXEC X_SET_PROP 'SAL_SFIN_SS_CODE', 'CONTROL_NAME_EDIT', 'Asel_spr15'
GO
EXEC X_SET_PROP 'SAL_SFIN_SS_CODE', 'COMMENTARY', 'На этот источник заменяются источники в начислениях страховых взносов и пособиях за счет ФСС.'
GO

GO
EXEC SA_SET_STATIC_NASTR '2016'

GO

GO
-- Отчет "Справка 2-НДФЛ для физлиц с договорами ГПХ"
-- Сгенерировано скриптом scriptObjectVar 'SQL_REPORT_2NDFL_FACE_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= 'SQL_REPORT_2NDFL_FACE_DGH'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SQL_REPORT_2NDFL_FACE_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'),
	'Справка 2-НДФЛ для физлиц с договорами ГПХ',NULL, 
	(Select link from object_var where code = 'SQL_REPORT_CATALOG_SALARY'),
	'SQL_REPORT_2NDFL_FACE_DGH',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'declare @nSummForCheck numeric(18,2)

if len(ltrim(rtrim(@cText5)))= 0
begin 
   select @cText5 = null
end

if isnumeric(ltrim(rtrim(@cText5))) = 0 
begin 	
	select @cText5 = null
end
	select @cText5 =  REPLACE(ltrim(rtrim(@cText5)),'','',''.'');
	select  @nSummForCheck  =  cast(ltrim(rtrim(@cText5))  as numeric(18,2)) 
			 

EXEC dbo.SD_REP_2NDFL
	@cText1					/* Расчетный год */,
	@cText2					/* Начинать нумерацию справок с */,
	@nCheck1 				/* Определить перечисленную сумму по проводкам */,
	@nSummForCheck  		/* Перечисленная сумма НДФЛ за период */,
	'''',  0,	/* Используется при другом способе вызова отчета */
	'''',  0,	/* Используется при другом способе вызова отчета */
	NULL, /*Отбор сотрудника*/
	@nMonth1 /* По месяц */,
	@nSel_Spr1 /*Отбор физлица*/'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#SD_REP_2NDFL'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH'),
	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_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(kir_2ndfl_prepare_report(),"2NDFL-DATA1.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #SD_REP_2NDFL
	@cText2 varchar(8000)	/* Номер справки */,
	@nSel_Spr1 int	/* Сотрудник */,
	@cText1 varchar(8000)	/* Расчетный год */,
	@nMonth1 int	/* По месяц */,
	@cText4 varchar(8000)	/* Признак */,
	@nCheck1 int	/* Определить перечисленную сумму по проводкам */,
	@cText5 varchar(8000)	/* Перечисленная сумма НДФЛ за период */,
	@nOption1 int	/* Форма */
AS
BEGIN

declare @nSummForCheck numeric(18,2)

if len(ltrim(rtrim(@cText5)))= 0
begin 
   select @cText5 = null
end

if isnumeric(ltrim(rtrim(@cText5))) = 0 
begin 	
	select @cText5 = null
end
	select @cText5 =  REPLACE(ltrim(rtrim(@cText5)),'','',''.'');
	select  @nSummForCheck  =  cast(ltrim(rtrim(@cText5))  as numeric(18,2)) 

EXEC dbo.SD_REP_2NDFL
	@cText1					/* Расчетный год */,
	@cText2					/* Начинать нумерацию справок с */,
	@nCheck1 				/* Определить перечисленную сумму по проводкам */,
	@nSummForCheck  		/* Перечисленная сумма НДФЛ за период */,
	'''',  0,	/* Используется при другом способе вызова отчета */
	'''',  0,	/* Используется при другом способе вызова отчета */
	NULL, /*Отбор сотрудника*/
	@nMonth1 /* По месяц */,
	@nSel_Spr1 /*Отбор физлица*/

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH'),
	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_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ALTERNATIVE_PRINT_METHOD')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE_DGH'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ALTERNATIVE_PRINT_METHOD'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_DGH_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_REPORT_2NDFL_FACE_DGH'),
		'SQL_REPORT_2NDFL_FACE_DGH_NASTR',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_DGH_N2' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_TEXTBOX'),
					'Номер справки',2, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_NASTR'),
					'SQL_REPORT_2NDFL_FACE_DGH_N2',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Номер справки'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'2'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText2'
						
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_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(8000)'
						
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_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'1'

						
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_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_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_LSEL_SPR'),
					'Сотрудник',3, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_NASTR'),
					'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'LSel_Spr'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'3'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KU_EMPL_PLACING'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
						
						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_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
						
						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_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_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 = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_DGH_N1' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_TEXTBOX'),
					'Расчетный год',4, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_NASTR'),
					'SQL_REPORT_2NDFL_FACE_DGH_N1',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(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_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Расчетный год'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(8000)'
						
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_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_DGH_N3' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_MONTHBOX'),
					'По месяц',5, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_NASTR'),
					'SQL_REPORT_2NDFL_FACE_DGH_N3',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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'MONTHBOX'
						
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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nMonth1'
						
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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(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_REPORT_2NDFL_FACE_DGH_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_DGH_N4' 
					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'),
					'Признак',6, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_NASTR'),
					'SQL_REPORT_2NDFL_FACE_DGH_N4',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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'4'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText4'
						
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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(8000)'
						
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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'1'
						
						
						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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'1'
						
						
						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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'1'
						
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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(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_REPORT_2NDFL_FACE_DGH_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_DGH_N5' 
					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'),
					'Определить перечисленную сумму по проводкам',8, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_NASTR'),
					'SQL_REPORT_2NDFL_FACE_DGH_N5',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_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(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_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(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_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(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_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(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_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(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_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(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_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(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_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(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_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(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_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(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_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(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_REPORT_2NDFL_FACE_DGH_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N5'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_DGH_N6' 
					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'),
					'Перечисленная сумма НДФЛ за период',9, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_NASTR'),
					'SQL_REPORT_2NDFL_FACE_DGH_N6',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_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(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_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(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_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(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_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(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_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(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_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'5'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(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_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(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_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText5'
						
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_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(8000)'
						
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_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(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_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(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_REPORT_2NDFL_FACE_DGH_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N6'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO

/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_DGH_N7' 
					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'),
					'Форма',7, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_NASTR'),
					'SQL_REPORT_2NDFL_FACE_DGH_N7',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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(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_REPORT_2NDFL_FACE_DGH_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_DGH_N7'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO

GO
-- Отчет "Справка 2-НДФЛ"
-- Сгенерировано скриптом scriptObjectVar 'SQL_REPORT_2NDFL_FACE'

/*** Сам отчет ***/

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

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SQL_REPORT_2NDFL_FACE'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Справка 2-НДФЛ',NULL, 
	(Select link from object_var where code = 'SQL_REPORT_CATALOG_SALARY'),
	'SQL_REPORT_2NDFL_FACE',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE') 
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'declare @nSummForCheck numeric(18,2)

if len(ltrim(rtrim(@cText5)))= 0
begin 
   select @cText5 = null
end

if isnumeric(ltrim(rtrim(@cText5))) = 0 
begin 	
	select @cText5 = null
end
	select @cText5 =  REPLACE(ltrim(rtrim(convert(varchar(16),@cText5))),'','',''.'');
	select  @nSummForCheck  =  cast(ltrim(rtrim(@cText5))  as numeric(18,2)) 
			 

EXEC dbo.SD_REP_2NDFL
	@cText1					/* Расчетный год */,
	@cText2					/* Начинать нумерацию справок с */,
	@nCheck1 				/* Определить перечисленную сумму по проводкам */,
	@nSummForCheck  		/* Перечисленная сумма НДФЛ за период */,
	'''',  0,	/* Используется при другом способе вызова отчета */
	'''',  0,	/* Используется при другом способе вызова отчета */
	@nSel_Spr1, /*Отбор сотрудника*/
	@nMonth1 /* По месяц */'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_DATETIME'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#SD_REP_2NDFL'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(kir_2ndfl_prepare_report(),"2NDFL-DATA1.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #SD_REP_2NDFL
	@cText2 varchar(8000)	/* Номер справки */,
	@nSel_Spr1 int	/* Сотрудник */,
	@cText1 varchar(8000)	/* Расчетный год */,
	@nMonth1 int	/* По месяц */,
	@cText4 varchar(8000)	/* Признак */,
	@nCheck1 int	/* Определить перечисленную сумму по проводкам */,
	@cText5 varchar(8000)	/* Перечисленная сумма НДФЛ за период */,
	@nOption1 int	/* Форма */
AS
BEGIN

declare @nSummForCheck numeric(18,2)

if len(ltrim(rtrim(@cText5)))= 0
begin 
   select @cText5 = null
end

if isnumeric(ltrim(rtrim(@cText5))) = 0 
begin 	
	select @cText5 = null
end
	select @cText5 =  REPLACE(ltrim(rtrim(convert(varchar(16),@cText5))),'','',''.'');
	select  @nSummForCheck  =  cast(ltrim(rtrim(@cText5))  as numeric(18,2)) 
			 

EXEC dbo.SD_REP_2NDFL
	@cText1					/* Расчетный год */,
	@cText2					/* Начинать нумерацию справок с */,
	@nCheck1 				/* Определить перечисленную сумму по проводкам */,
	@nSummForCheck  		/* Перечисленная сумма НДФЛ за период */,
	'''',  0,	/* Используется при другом способе вызова отчета */
	'''',  0,	/* Используется при другом способе вызова отчета */
	@nSel_Spr1, /*Отбор сотрудника*/
	@nMonth1 /* По месяц */

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	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_REPORT_2NDFL_FACE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ALTERNATIVE_PRINT_METHOD')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ALTERNATIVE_PRINT_METHOD'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_2NDFL_FACE') 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_REPORT_2NDFL_FACE'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_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_REPORT_2NDFL_FACE'),
		'SQL_REPORT_2NDFL_FACE_NASTR',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_N2' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_TEXTBOX'),
					'Номер справки',2, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_NASTR'),
					'SQL_REPORT_2NDFL_FACE_N2',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Номер справки'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'2'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText2'
						
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_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(8000)'
						
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_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'1'
						
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_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_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'),
					'Сотрудник',3, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_NASTR'),
					'SQL_REPORT_2NDFL_FACE_MAIN_PARAM',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Сотрудник'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'LSel_Spr'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'3'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KU_EMPL_PLACING'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_N1' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_TEXTBOX'),
					'Расчетный год',4, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_NASTR'),
					'SQL_REPORT_2NDFL_FACE_N1',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(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_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Расчетный год'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(8000)'
						
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_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_N3' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_MONTHBOX'),
					'По месяц',5, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_NASTR'),
					'SQL_REPORT_2NDFL_FACE_N3',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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'MONTHBOX'
						
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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nMonth1'
						
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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(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_REPORT_2NDFL_FACE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_N4' 
					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'),
					'Признак',6, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_NASTR'),
					'SQL_REPORT_2NDFL_FACE_N4',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_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(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_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(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_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(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_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(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_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(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_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'4'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(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_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(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_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText4'
						
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_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(8000)'
						
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_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'1'
						
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_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(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_REPORT_2NDFL_FACE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_N5' 
					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'),
					'Определить перечисленную сумму по проводкам',8, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_NASTR'),
					'SQL_REPORT_2NDFL_FACE_N5',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_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(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_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(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_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(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_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(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_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(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_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(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_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(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_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(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_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(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_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(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_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(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_REPORT_2NDFL_FACE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N5'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_N6' 
					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'),
					'Перечисленная сумма НДФЛ за период',9, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_NASTR'),
					'SQL_REPORT_2NDFL_FACE_N6',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_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(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_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(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_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(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_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(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_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(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_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'5'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(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_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(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_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText5'
						
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_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(8000)'
						
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_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(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_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(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_REPORT_2NDFL_FACE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N6'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_FACE_N7' 
					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'),
					'Форма',7, 
					(Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_NASTR'),
					'SQL_REPORT_2NDFL_FACE_N7',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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(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_REPORT_2NDFL_FACE_N7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_FACE_N7'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
-- Отчет "Сведения о доходах физических лиц"
-- Сгенерировано скриптом scriptObjectVar 'SQL_report_2ndfl'

/*** Сам отчет ***/

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

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SQL_report_2ndfl'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Сведения о доходах физических лиц',201, 
	(Select link from object_var where code = 'SQL_REPORT_CATALOG_SALARY'),
	'SQL_REPORT_2NDFL',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SQL_report_2ndfl') 
	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_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'INIT_OBJECT_METHOD'),
	VALUE= 'kir_export_query(nLink_Var)'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_DATETIME'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_FREEZEPANES'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_PAGES'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'declare @nSummForCheck numeric(18,2)

if len(ltrim(rtrim(@cText5)))= 0
begin 
   select @cText5 = null
end

if isnumeric(ltrim(rtrim(@cText5))) = 0 
begin 	
	select @cText5 = null
end
	select @cText5 =  REPLACE(ltrim(rtrim(convert(varchar(16),@cText5))),'','',''.'');
	select  @nSummForCheck  =  cast(ltrim(rtrim(@cText5))  as numeric(18,2)) 

			 
EXEC dbo.SD_REP_2NDFL
	@cText1					/* Расчетный год */,
	@cText3					/* Начинать нумерацию справок с */,
	@nCheck2 				/* Определить перечисленную сумму по проводкам */,
	@nSummForCheck 		/* Перечисленная сумма НДФЛ за период */,
	@cVal1,  @nOtborLink1,	/* Отбор сотрудников */
	@cVal2,  @nOtborLink2,	/* Отбор сотрудников */
	DEFAULT, /*Используется при другом способе вызова отчета	*/
	DEFAULT /*Используется при другом способе вызова отчета	*/

		
'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_DISTINCT'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_FREEZEPANES'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PAGES'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#REPORT_2NDFL'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(kir_2ndfl_prepare_report(),"2NDFL-DATA1.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #REPORT_2NDFL
	@cText1 varchar(4)	/* Расчетный год */,
	@nCheck1 int	/* Показать реестр */,
	@cText2 varchar(2)	/* Номер файла (реестра) */,
	@cText3 varchar(4)	/* Начинать нумерацию справок с */,
	@cText4 varchar(1)	/* Признак */,
	@nCheck2 int	/* Определить перечисленную сумму по проводкам */,
	@cText5 varchar(16)	/* Перечисленная сумма НДФЛ за период */,
	@nOption1 int	/* Форма */,
	@nFilterLink int	/* Фильтр */
AS
BEGIN
	DECLARE @cVal1 char(1), @nOtborLink1 int	/* Отбор сотрудников */
	SELECT @nOtborLink1 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE=''OTBOR_QUERY_SQL_EMPL''))
	SELECT @cVal1 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink1 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))
	DECLARE @cVal2 char(1), @nOtborLink2 int	/* Отбор внештатников */
	SELECT @nOtborLink2 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE=''OTBOR_QUERY_SQL_DGH''))
	SELECT @cVal2 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink2 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))


declare @nSummForCheck numeric(18,2)

if len(ltrim(rtrim(@cText5)))= 0
begin 
   select @cText5 = null
end

if isnumeric(ltrim(rtrim(@cText5))) = 0 
begin 	
	select @cText5 = null
end
	select @cText5 =  REPLACE(ltrim(rtrim(convert(varchar(16),@cText5))),'','',''.'');
	select  @nSummForCheck  =  cast(ltrim(rtrim(@cText5))  as numeric(18,2)) 

			 
EXEC dbo.SD_REP_2NDFL
	@cText1					/* Расчетный год */,
	@cText3					/* Начинать нумерацию справок с */,
	@nCheck2 				/* Определить перечисленную сумму по проводкам */,
	@nSummForCheck 		/* Перечисленная сумма НДФЛ за период */,
	@cVal1,  @nOtborLink1,	/* Отбор сотрудников */
	@cVal2,  @nOtborLink2,	/* Отбор сотрудников */
	DEFAULT, /*Используется при другом способе вызова отчета	*/
	DEFAULT /*Используется при другом способе вызова отчета	*/

		


END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'EOD_PROTOCOL'),
	VALUE= 'PROTOCOLS_EOD_2NDFL#1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'AFTER_REPORT_PROG'),
	VALUE= 'KIR_2NDFL_AFTER_REP(oForm)'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	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_report_2ndfl') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ALTERNATIVE_PRINT_METHOD')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ALTERNATIVE_PRINT_METHOD'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_report_2ndfl') 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_report_2ndfl'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'OTBOR_QUERY_SQL_EMPL' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_FILTER'),
		'Стандартный фильтр для запроса',NULL, 
		(Select link from object_var where code = 'SQL_REPORT_2NDFL'),
		'OTBOR_QUERY_SQL_EMPL',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'W400311' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'OTBOR_QUERY_SQL_DGH'),
					'Отбор внештатников',2, 
					(Select link from object_var where code = 'OTBOR_QUERY_SQL_EMPL'),
					'W400311',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'W400311') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400311'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_CHECK') and LINK_UP = (Select link from object_var where code = 'W400311') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400311'),
							(Select link from s_property where code = 'QUERY_OTBOR_CHECK'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE') and LINK_UP = (Select link from object_var where code = 'W400311') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400311'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE'),
							'DICTIONARY_PERSONS_DGH'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_FIELD') and LINK_UP = (Select link from object_var where code = 'W400311') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400311'),
							(Select link from s_property where code = 'QUERY_OTBOR_FIELD'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE') and LINK_UP = (Select link from object_var where code = 'W400311') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400311'),
							(Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_VALUE') and LINK_UP = (Select link from object_var where code = 'W400311') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400311'),
							(Select link from s_property where code = 'QUERY_OTBOR_VALUE'),
							''
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'W400312' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'OTBOR_QUERY_SQL_EMPL'),
					'Отбор сотрудников',1, 
					(Select link from object_var where code = 'OTBOR_QUERY_SQL_EMPL'),
					'W400312',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'W400312') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400312'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_CHECK') and LINK_UP = (Select link from object_var where code = 'W400312') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400312'),
							(Select link from s_property where code = 'QUERY_OTBOR_CHECK'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE') and LINK_UP = (Select link from object_var where code = 'W400312') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400312'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE'),
							'DICT_EMPLOYERS01'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_FIELD') and LINK_UP = (Select link from object_var where code = 'W400312') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400312'),
							(Select link from s_property where code = 'QUERY_OTBOR_FIELD'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE') and LINK_UP = (Select link from object_var where code = 'W400312') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400312'),
							(Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_VALUE') and LINK_UP = (Select link from object_var where code = 'W400312') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400312'),
							(Select link from s_property where code = 'QUERY_OTBOR_VALUE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE2') and LINK_UP = (Select link from object_var where code = 'W400312') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'W400312'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE2'),
							'DICTIONARY_SUBDIVISION01'
						
GO
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_REPRT_2NDFL_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 = 'SQL_REPORT_2NDFL'),
		'SQL_REPRT_2NDFL_NASTR_GR',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_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_TEXTBOX'),
					'Расчетный год',2, 
					(Select link from object_var where code = 'SQL_REPRT_2NDFL_NASTR_GR'),
					'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR1'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
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_REPORT_2NDFL_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR1'),
							(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_REPORT_2NDFL_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(4)'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'2013'

						
GO
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_REPORT_2NDFL_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_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_CHECKBOX'),
					'Показать реестр',3, 
					(Select link from object_var where code = 'SQL_REPRT_2NDFL_NASTR_GR'),
					'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR2'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
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_REPORT_2NDFL_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_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_REPORT_2NDFL_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Вкл.'

						
GO
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_REPORT_2NDFL_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_NASTR3' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_TEXTBOX'),
					'Номер файла (реестра)',4, 
					(Select link from object_var where code = 'SQL_REPRT_2NDFL_NASTR_GR'),
					'SQL_REPORT_2NDFL_NASTR3',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
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_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Номер файла (реестра)'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'2'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText2'
						
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_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(3)'
						
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_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'1'
						
						
						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_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'1'
						
GO
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_REPORT_2NDFL_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_NASTR4' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_TEXTBOX'),
					'Начинать нумерацию справок с',5, 
					(Select link from object_var where code = 'SQL_REPRT_2NDFL_NASTR_GR'),
					'SQL_REPORT_2NDFL_NASTR4',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
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_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(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_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'3'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(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_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText3'
						
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_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(4)'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'1'
						
						
						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_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'1'
						
GO
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_REPORT_2NDFL_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_NASTR5' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_TEXTBOX'),
					'Признак',6, 
					(Select link from object_var where code = 'SQL_REPRT_2NDFL_NASTR_GR'),
					'SQL_REPORT_2NDFL_NASTR5',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(Select link from s_property where code = 'EDITABLE'),
							'1'
						
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_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(Select link from s_property where code = 'FORMAT'),
							'[1-2]'
						
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_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(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_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'4'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(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_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText4'
						
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_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(1)'
						
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_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'1'

						
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_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR5'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_NASTR8' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_OPTIONGROUP'),
					'Форма',7, 
					(Select link from object_var where code = 'SQL_REPRT_2NDFL_NASTR_GR'),
					'SQL_REPORT_2NDFL_NASTR8',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Форма корректировки'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(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_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(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_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Первичная,Корректирующая,Аннулирующая'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(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_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Первичная'

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR8'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_NASTR6' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Определить перечисленную сумму по проводкам',8, 
					(Select link from object_var where code = 'SQL_REPRT_2NDFL_NASTR_GR'),
					'SQL_REPORT_2NDFL_NASTR6',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(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_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'2'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(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_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck2'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'
			
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR6'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_2NDFL_NASTR7' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_TEXTBOX'),
					'Перечисленная сумма НДФЛ за период',9, 
					(Select link from object_var where code = 'SQL_REPRT_2NDFL_NASTR_GR'),
					'SQL_REPORT_2NDFL_NASTR7',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Перечисленная сумма НДФЛ за период'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'5'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText5'
						
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_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(16)'
						
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_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_2NDFL_NASTR7'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO


GO
EXEC X_SET_PROP 'STO_WHT_CODE_KBK', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
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 (6711.00, 'Повышение квалификации', 2688.00, 'SYS_POV_KVALIF', NULL, 0.00, NULL, NULL, 'SQUERY_USER', NULL, NULL, 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6712.00, 'Организация - ключ', 2686.00, 'SYS_POV_KVALIF_LINK_DEP', NULL, 999.00, 6711.00, 3423.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF', '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 (6721.00, 'Лицо', 2686.00, 'SYS_POV_KVALIF_LINK_FACE', NULL, 999.00, 6711.00, 1359.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF', 'SYS_2452328_0LV0IROM7', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6739.00, 'Повышение квалификации - запись', 2686.00, 'SYS_POV_KVALIF_LINK_KVAL', NULL, 999.00, 6711.00, 1977.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF', 'SYS_2452418_0OD0ZF7ZH', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6761.00, 'Запись штатного расписания', 2686.00, 'SYS_POV_KVALIF_LINK_STAFF', NULL, 999.00, 6711.00, 1494.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF', 'SYS_2452364_0MV0NQUS9', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6781.00, 'Дата формирования', 2698.00, 'SYS_POV_KVALIF_NASTR1', NULL, 1.00, 6711.00, NULL, 'SQUERY_NASTR', 'SYS_POV_KVALIF', NULL, 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6782.00, 'Начало периода', 2698.00, 'SYS_POV_KVALIF_NASTR2', NULL, 2.00, 6711.00, NULL, 'SQUERY_NASTR', 'SYS_POV_KVALIF', NULL, 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6783.00, 'Конец периода', 2698.00, 'SYS_POV_KVALIF_NASTR3', NULL, 3.00, 6711.00, NULL, 'SQUERY_NASTR', 'SYS_POV_KVALIF', NULL, 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (20321.00, 'Выводить итоги', 2698.00, 'SYS_POV_KVALIF_NASTR4', NULL, 4.00, 6711.00, NULL, 'SQUERY_NASTR', 'SYS_POV_KVALIF', NULL, 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6351.00, 'Наименование образовательного учреждения', 2686.00, 'SYS_POV_KVALIF_KVAL_DEP', NULL, 999.00, 6739.00, 6043.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_KVAL', 'SYS_2452756_0XT0T5OYC', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6713.00, '', 2693.00, 'SYS_POV_KVALIF_LINK_DEP_F1', NULL, 0.00, 6712.00, 3423.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_LINK_DEP', '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 (6714.00, '', 2691.00, 'SYS_POV_KVALIF_LINK_DEP_F2', NULL, 0.00, 6712.00, 3423.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_LINK_DEP', '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 (6715.00, '', 2695.00, 'SYS_POV_KVALIF_LINK_DEP_F3', NULL, 0.00, 6712.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_LINK_DEP', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6716.00, 'Организация', 2686.00, 'SYS_POV_KVALIF_LINK_DEP_DEP', NULL, 1.00, 6712.00, 3426.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_DEP', 'SYS_2452558_0S90YIGV9', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6720.00, '', 2694.00, 'SYS_POV_KVALIF_LINK_DEP_F4', NULL, 0.00, 6712.00, 4000.00, 'SQUERY_LINK_STATE', 'SYS_POV_KVALIF_LINK_DEP', '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 (6722.00, '', 2693.00, 'SYS_POV_KVALIF_LINK_FACE_F1', NULL, 0.00, 6721.00, 1359.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_LINK_FACE', 'SYS_2452328_0LV0IROM7', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6723.00, '', 2691.00, 'SYS_POV_KVALIF_LINK_FACE_F2', NULL, 0.00, 6721.00, 1359.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_LINK_FACE', 'SYS_2452328_0LV0IROM7', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6724.00, '', 2695.00, 'SYS_POV_KVALIF_LINK_FACE_F3', NULL, 0.00, 6721.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_LINK_FACE', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6725.00, 'Фамилия', 2686.00, 'SYS_POV_KVALIF_LINK_FACE_FM', NULL, 4.00, 6721.00, 1361.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_FACE', 'SYS_2452328_0LV0ITQUN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6729.00, 'Имя', 2686.00, 'SYS_POV_KVALIF_LINK_FACE_IM', NULL, 6.00, 6721.00, 1362.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_FACE', 'SYS_2452328_0LV0IU1GV', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6733.00, 'Отчество', 2686.00, 'SYS_POV_KVALIF_LINK_FACE_OT', NULL, 7.00, 6721.00, 1363.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_FACE', 'SYS_2452328_0LV0IU4O1', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6737.00, '', 2694.00, 'SYS_POV_KVALIF_LINK_FACE_F4', NULL, 0.00, 6721.00, 4038.00, 'SQUERY_LINK_STATE', 'SYS_POV_KVALIF_LINK_FACE', 'SYS_2452566_0SH0LW148', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6738.00, '', 2694.00, 'SYS_POV_KVALIF_LINK_FACE_F5', NULL, 1.00, 6721.00, 5650.00, 'SQUERY_LINK_STATE', 'SYS_POV_KVALIF_LINK_FACE', 'SYS_2452696_0W50V0X1F', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6740.00, '', 2693.00, 'SYS_POV_KVALIF_LINK_KVAL_F1', NULL, 0.00, 6739.00, 1977.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_LINK_KVAL', 'SYS_2452418_0OD0ZF7ZH', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6741.00, '', 2691.00, 'SYS_POV_KVALIF_LINK_KVAL_F2', NULL, 0.00, 6739.00, 1977.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_LINK_KVAL', 'SYS_2452418_0OD0ZF7ZH', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6742.00, '', 2695.00, 'SYS_POV_KVALIF_LINK_KVAL_F3', NULL, 0.00, 6739.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_LINK_KVAL', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6743.00, 'Дата начала обучения', 2686.00, 'SYS_POV_KVALIF_KVAL_D1', NULL, 8.00, 6739.00, 1978.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_KVAL', 'SYS_2452418_0OD0ZINOA', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6747.00, 'Дата окончания обучения', 2686.00, 'SYS_POV_KVALIF_KVAL_D2', NULL, 9.00, 6739.00, 1979.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_KVAL', 'SYS_2452418_0OD0ZIQLZ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6751.00, '', 2694.00, 'SYS_POV_KVALIF_LINK_KVAL_F4', NULL, 0.00, 6739.00, 4212.00, 'SQUERY_LINK_STATE', 'SYS_POV_KVALIF_LINK_KVAL', 'SYS_2452573_0SO0VVGTU', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6752.00, '', 2694.00, 'SYS_POV_KVALIF_LINK_KVAL_F5', NULL, 1.00, 6739.00, 4219.00, 'SQUERY_LINK_STATE', 'SYS_POV_KVALIF_LINK_KVAL', 'SYS_2452573_0SO0W2KGA', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6753.00, 'Номер документа', 2686.00, 'SYS_POV_KVALIF_KVAL_DOC', NULL, 10.00, 6739.00, 1982.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_KVAL', 'SYS_2452418_0OD0ZIZ5D', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6757.00, 'Вид повышения квалификации', 2686.00, 'SYS_POV_KVALIF_KVAL_TYPE', NULL, 2.00, 6739.00, 1980.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_KVAL', 'SYS_2452418_0OD0ZIT9Y', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6762.00, '', 2693.00, 'SYS_POV_KVALIF_LINK_STAFF_F1', NULL, 0.00, 6761.00, 1494.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_LINK_STAFF', 'SYS_2452364_0MV0NQUS9', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6763.00, '', 2691.00, 'SYS_POV_KVALIF_LINK_STAFF_F2', NULL, 0.00, 6761.00, 1494.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_LINK_STAFF', 'SYS_2452364_0MV0NQUS9', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6764.00, '', 2695.00, 'SYS_POV_KVALIF_LINK_STAFF_F3', NULL, 0.00, 6761.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_LINK_STAFF', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6765.00, 'Подразделение', 2686.00, 'SYS_POV_KVALIF_STAFF_SUB', NULL, 11.00, 6761.00, 1495.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_STAFF', 'SYS_2452364_0MV0NSE3G', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6769.00, 'Подразделение - код', 2686.00, 'SYS_POV_KVALIF_STAFF_SBC', NULL, 999.00, 6761.00, 1496.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_STAFF', 'SYS_2452364_0MV0NUYMN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6773.00, 'Подразделение - порядок', 2686.00, 'SYS_POV_KVALIF_STAFF_ORD', NULL, 3.00, 6761.00, 1497.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_STAFF', 'SYS_2452364_0MV0NVO6A', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6777.00, 'Подразделение - уровень', 2686.00, 'SYS_POV_KVALIF_STAFF_SBL', NULL, 999.00, 6761.00, 1498.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_STAFF', 'SYS_2452364_0MV0NW2D1', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6784.00, 'Должность', 2686.00, 'SYS_POV_KVALIF_STAFF_POST', NULL, 5.00, 6761.00, 1499.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_STAFF', 'SYS_2452364_0MV0NX5SA', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (17037.00, '', 2694.00, 'SYS_2453018_15514L6CT', NULL, 0.00, 6761.00, 3365.00, 'SQUERY_LINK_STATE', 'SYS_POV_KVALIF_LINK_STAFF', 'SYS_2452554_0S50QSXCK', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (17038.00, '', 2694.00, 'SYS_2453018_15514L6EG', NULL, 1.00, 6761.00, 3367.00, 'SQUERY_LINK_STATE', 'SYS_POV_KVALIF_LINK_STAFF', 'SYS_2452554_0S50QUJM1', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (17853.00, 'Наименование курса', 2686.00, '041FFD3C-1026-42B9-9E05-30D01A872C6C', NULL, 999.00, 6739.00, 18228.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_KVAL', 'SYS_0154DB9A-8D4B-49E1-8DF6-E19BD24114A3', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (19552.00, 'Количество часов обучения', 2686.00, 'SYS_POV_KVALIF_KVAL_QH', NULL, 999.00, 6739.00, 19541.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_KVAL', 'SYS_FD9BF4CD-10F5-4089-902B-8402E7F63CAB', 0)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (19553.00, 'ФИО', 2686.00, 'SYS_POV_KVALIF_LINK_FACE_FIO', NULL, 999.00, 6721.00, 1364.00, 'SQUERY_FIELD', 'SYS_POV_KVALIF_LINK_FACE', 'SYS_2452328_0LV0IUCIO', 0)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6352.00, '', 2693.00, 'SYS_POV_KVALIF_KVAL_DEP_F1', NULL, 0.00, 6351.00, 6043.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_KVAL_DEP', 'SYS_2452756_0XT0T5OYC', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6353.00, '', 2691.00, 'SYS_POV_KVALIF_KVAL_DEP_F2', NULL, 0.00, 6351.00, 6043.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_KVAL_DEP', 'SYS_2452756_0XT0T5OYC', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6354.00, '', 2695.00, 'SYS_POV_KVALIF_KVAL_DEP_F3', NULL, 0.00, 6351.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_KVAL_DEP', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6717.00, '', 2693.00, 'SYS_POV_KVALIF_LINK_DEP_DEP_F1', NULL, 0.00, 6716.00, 3426.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SYS_2452558_0S90YIGV9', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6718.00, '', 2691.00, 'SYS_POV_KVALIF_LINK_DEP_DEP_F2', NULL, 0.00, 6716.00, 3426.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SYS_2452558_0S90YIGV9', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6719.00, '', 2695.00, 'SYS_POV_KVALIF_LINK_DEP_DEP_F3', NULL, 0.00, 6716.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6726.00, '', 2693.00, 'SYS_POV_KVALIF_LINK_FACE_FM_F1', NULL, 0.00, 6725.00, 1361.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_LINK_FACE_FM', 'SYS_2452328_0LV0ITQUN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6727.00, '', 2691.00, 'SYS_POV_KVALIF_LINK_FACE_FM_F2', NULL, 0.00, 6725.00, 1361.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_LINK_FACE_FM', 'SYS_2452328_0LV0ITQUN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6728.00, '', 2695.00, 'SYS_POV_KVALIF_LINK_FACE_FM_F3', NULL, 0.00, 6725.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_LINK_FACE_FM', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6730.00, '', 2693.00, 'SYS_POV_KVALIF_LINK_FACE_IM_F1', NULL, 0.00, 6729.00, 1362.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_LINK_FACE_IM', 'SYS_2452328_0LV0IU1GV', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6731.00, '', 2691.00, 'SYS_POV_KVALIF_LINK_FACE_IM_F2', NULL, 0.00, 6729.00, 1362.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_LINK_FACE_IM', 'SYS_2452328_0LV0IU1GV', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6732.00, '', 2695.00, 'SYS_POV_KVALIF_LINK_FACE_IM_F3', NULL, 0.00, 6729.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_LINK_FACE_IM', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6734.00, '', 2693.00, 'SYS_POV_KVALIF_LINK_FACE_OT_F1', NULL, 0.00, 6733.00, 1363.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_LINK_FACE_OT', 'SYS_2452328_0LV0IU4O1', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6735.00, '', 2691.00, 'SYS_POV_KVALIF_LINK_FACE_OT_F2', NULL, 0.00, 6733.00, 1363.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_LINK_FACE_OT', 'SYS_2452328_0LV0IU4O1', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6736.00, '', 2695.00, 'SYS_POV_KVALIF_LINK_FACE_OT_F3', NULL, 0.00, 6733.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_LINK_FACE_OT', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6744.00, '', 2693.00, 'SYS_POV_KVALIF_KVAL_D1_F1', NULL, 0.00, 6743.00, 1978.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_KVAL_D1', 'SYS_2452418_0OD0ZINOA', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6745.00, '', 2691.00, 'SYS_POV_KVALIF_KVAL_D1_F2', NULL, 0.00, 6743.00, 1978.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_KVAL_D1', 'SYS_2452418_0OD0ZINOA', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6746.00, '', 2695.00, 'SYS_POV_KVALIF_KVAL_D1_F3', NULL, 0.00, 6743.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_KVAL_D1', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6748.00, '', 2693.00, 'SYS_POV_KVALIF_KVAL_D2_F1', NULL, 0.00, 6747.00, 1979.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_KVAL_D2', 'SYS_2452418_0OD0ZIQLZ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6749.00, '', 2691.00, 'SYS_POV_KVALIF_KVAL_D2_F2', NULL, 0.00, 6747.00, 1979.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_KVAL_D2', 'SYS_2452418_0OD0ZIQLZ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6750.00, '', 2695.00, 'SYS_POV_KVALIF_KVAL_D2_F3', NULL, 0.00, 6747.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_KVAL_D2', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6754.00, '', 2693.00, 'SYS_POV_KVALIF_KVAL_DOC_F1', NULL, 0.00, 6753.00, 1982.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_KVAL_DOC', 'SYS_2452418_0OD0ZIZ5D', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6755.00, '', 2691.00, 'SYS_POV_KVALIF_KVAL_DOC_F2', NULL, 0.00, 6753.00, 1982.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_KVAL_DOC', 'SYS_2452418_0OD0ZIZ5D', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6756.00, '', 2695.00, 'SYS_POV_KVALIF_KVAL_DOC_F3', NULL, 0.00, 6753.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_KVAL_DOC', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6758.00, '', 2693.00, 'SYS_POV_KVALIF_KVAL_TYPE_F1', NULL, 0.00, 6757.00, 1980.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_KVAL_TYPE', 'SYS_2452418_0OD0ZIT9Y', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6759.00, '', 2691.00, 'SYS_POV_KVALIF_KVAL_TYPE_F2', NULL, 0.00, 6757.00, 1980.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_KVAL_TYPE', 'SYS_2452418_0OD0ZIT9Y', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6760.00, '', 2695.00, 'SYS_POV_KVALIF_KVAL_TYPE_F3', NULL, 0.00, 6757.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_KVAL_TYPE', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16157.00, '', 2693.00, 'SYS_2452728_0X10QKUG1', NULL, 0.00, 6765.00, 1495.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_STAFF_SUB', 'SYS_2452364_0MV0NSE3G', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16158.00, '', 2693.00, 'SYS_2452728_0X10QKW0G', NULL, 0.00, 6769.00, 1496.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_STAFF_SBC', 'SYS_2452364_0MV0NUYMN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16159.00, '', 2693.00, 'SYS_2452728_0X10QKXT7', NULL, 0.00, 6773.00, 1497.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_STAFF_ORD', 'SYS_2452364_0MV0NVO6A', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16160.00, '', 2693.00, 'SYS_2452728_0X10QKZQ5', NULL, 0.00, 6777.00, 1498.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_STAFF_SBL', 'SYS_2452364_0MV0NW2D1', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16161.00, '', 2693.00, 'SYS_2452728_0X10QLONR', NULL, 0.00, 6784.00, 1499.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_STAFF_POST', 'SYS_2452364_0MV0NX5SA', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16499.00, '', 2691.00, 'SYS_2452728_0X10QKW1D', NULL, 0.00, 6769.00, 1496.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_STAFF_SBC', 'SYS_2452364_0MV0NUYMN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16500.00, '', 2691.00, 'SYS_2452728_0X10QKXUF', NULL, 0.00, 6773.00, 1497.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_STAFF_ORD', 'SYS_2452364_0MV0NVO6A', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16501.00, '', 2691.00, 'SYS_2452728_0X10QKZR1', NULL, 0.00, 6777.00, 1498.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_STAFF_SBL', 'SYS_2452364_0MV0NW2D1', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16502.00, '', 2691.00, 'SYS_2452728_0X10QLOP0', NULL, 0.00, 6784.00, 1499.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_STAFF_POST', 'SYS_2452364_0MV0NX5SA', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16505.00, '', 2691.00, 'SYS_2452728_0X10QKUGX', NULL, 0.00, 6765.00, 1495.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_STAFF_SUB', 'SYS_2452364_0MV0NSE3G', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16809.00, '', 2695.00, 'SYS_2452728_0X10QLOQB', NULL, 0.00, 6784.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_STAFF_POST', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16815.00, '', 2695.00, 'SYS_2452728_0X10QKUI8', NULL, 0.00, 6765.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_STAFF_SUB', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16816.00, '', 2695.00, 'SYS_2452728_0X10QKW2N', NULL, 0.00, 6769.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_STAFF_SBC', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16817.00, '', 2695.00, 'SYS_2452728_0X10QKXVR', NULL, 0.00, 6773.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_STAFF_ORD', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (16818.00, '', 2695.00, 'SYS_2452728_0X10QKZSC', NULL, 0.00, 6777.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_STAFF_SBL', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (17854.00, '', 2695.00, '3EBD5CFC-3841-484B-B41A-5CDDDF9001F7', NULL, 0.00, 17853.00, 6711.00, 'SQUERY_LINK_SQUERY', '041FFD3C-1026-42B9-9E05-30D01A872C6C', 'SYS_POV_KVALIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (17855.00, '', 2691.00, '555F7030-AA87-4A7E-9F1D-06D0C523832A', NULL, 0.00, 17853.00, 18228.00, 'SQUERY_LINK_SOURCE', '041FFD3C-1026-42B9-9E05-30D01A872C6C', 'SYS_0154DB9A-8D4B-49E1-8DF6-E19BD24114A3', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (17856.00, '', 2693.00, 'BF0F2C06-DFD4-4A2F-8601-B519D32810F6', NULL, 0.00, 17853.00, 18228.00, 'SQUERY_LINK_BASE', '041FFD3C-1026-42B9-9E05-30D01A872C6C', 'SYS_0154DB9A-8D4B-49E1-8DF6-E19BD24114A3', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (19546.00, '', 2691.00, '3AF93FA6-040D-4EF3-94BE-F0352F093A83', NULL, 0.00, 19553.00, 1364.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SYS_2452328_0LV0IUCIO', 0)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (19547.00, '', 2691.00, '3CA8725D-381A-46F2-AAFE-6D73FEE3FFFC', NULL, 0.00, 19552.00, 19541.00, 'SQUERY_LINK_SOURCE', 'SYS_POV_KVALIF_KVAL_QH', 'SYS_FD9BF4CD-10F5-4089-902B-8402E7F63CAB', 0)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (19548.00, '', 2695.00, '44209C65-BCB6-48FA-912E-6335EB06853B', NULL, 0.00, 19552.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_KVAL_QH', 'SYS_POV_KVALIF', 0)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (19549.00, '', 2693.00, '898702FD-43EA-409F-90E3-3A030812944C', NULL, 0.00, 19553.00, 1364.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SYS_2452328_0LV0IUCIO', 0)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (19550.00, '', 2695.00, 'E66DFEAB-85EA-4B53-A46A-62392E3AA390', NULL, 0.00, 19553.00, 6711.00, 'SQUERY_LINK_SQUERY', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SYS_POV_KVALIF', 0)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (19551.00, '', 2693.00, 'EF58A797-1875-4F9A-8AF7-CE444A2F50BC', NULL, 0.00, 19552.00, 19541.00, 'SQUERY_LINK_BASE', 'SYS_POV_KVALIF_KVAL_QH', 'SYS_FD9BF4CD-10F5-4089-902B-8402E7F63CAB', 0)

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 (6351.00, 139.00, NULL, NULL, 'S_27669', 'SYS_POV_KVALIF_KVAL_DEP', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6351.00, 140.00, NULL, NULL, '3', 'SYS_POV_KVALIF_KVAL_DEP', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6351.00, 141.00, NULL, NULL, '', 'SYS_POV_KVALIF_KVAL_DEP', 'SQUERY_FIELD_FORMAT_C_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6351.00, 142.00, NULL, NULL, 'Основной', 'SYS_POV_KVALIF_KVAL_DEP', 'SQUERY_FIELD_FORMAT_D_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6351.00, 148.00, NULL, NULL, '8', 'SYS_POV_KVALIF_KVAL_DEP', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6351.00, 151.00, NULL, NULL, '1', 'SYS_POV_KVALIF_KVAL_DEP', 'SQUERY_FIELD_SORT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6351.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_KVAL_DEP', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6351.00, 156.00, NULL, NULL, '40', 'SYS_POV_KVALIF_KVAL_DEP', 'SQUERY_FIELD_WIDTH_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 137.00, NULL, NULL, '', 'SYS_POV_KVALIF', 'SQUERY_CHANGED')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 157.00, NULL, NULL, '', 'SYS_POV_KVALIF', 'SQUERY_FOOTER')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 159.00, NULL, NULL, 'REPMAKER_Q.XLS', 'SYS_POV_KVALIF', 'SQUERY_GENERATOR')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 174.00, NULL, NULL, 'IIF(@nCheck_1 = 0,"REPQUERY_2.XLT",IIF(@nCheck_1 = 1,"REPQUERY.XLT",""))', 'SYS_POV_KVALIF', 'SQUERY_REPORT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 15.00, '
	UPDATE #T_RES
	SET	S_26598 = (SELECT TYPE FROM  #QUALIFY WHERE ID=S_26579 )
 /*Вид повышения квалификации*/ FROM #T_RES T 
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 5.00, '
	CREATE TABLE #T_RES (S_26550 INT /*Организация - ключ*/,
		S_26555 VARCHAR(120) /*Организация*/,
		S_26560 INT /*Лицо*/,
		S_26565 VARCHAR(100) /*Фамилия*/,
		S_26569 VARCHAR(100) /*Имя*/,
		S_26573 VARCHAR(100) /*Отчество*/,
		S_26579 int /*Повышение квалификации - запись*/,
		S_26584 DATETIME /*Дата начала обучения*/,
		S_26588 DATETIME /*Дата окончания обучения*/,
		S_26594 VARCHAR(254) /*Номер документа*/,
		S_26598 VARCHAR(254) /*Вид повышения квалификации*/,
		S_26602 int /*Запись штатного расписания*/,
		S_26607 VARCHAR(254) /*Подразделение*/,
		S_26611 VARCHAR(5) /*Подразделение - код*/,
		S_26615 INT /*Подразделение - порядок*/,
		S_26619 INT /*Подразделение - уровень*/,
		S_26628 VARCHAR(254) /*Должность*/,
		S_27669 VARCHAR(254) /*Наименование образовательного учреждения*/,
		S_87614 VARCHAR(500) /*Наименование курса*/,
		S_91903 INT /*Количество часов обучения*/,
		S_91913 VARCHAR(150) /*ФИО*/, SQUERY int)
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 6.00, '
	INSERT #T_RES (S_26550, S_26560, S_26579, S_26602, S_26615, S_26628, S_26611, S_26619, S_26607, SQUERY) /*Подразделение*/
	SELECT DEP.LINK, #workers.face, Q.ID, #STAFF.LNK, #staff.num_otd, #staff.POST_NAME, #staff.SUBDIV_CODE, #STAFF.LEVEL_OTD, #staff.SUBDIV_NAME, 86829
	FROM #STAFF, #WORKERS, #QUALIFY Q, DICTIONARY_DEPARTMENT DEP
	WHERE #STAFF.LINK_DEP=DEP.LINK
		AND #WORKERS.LINK_DEP=DEP.LINK
		AND (#staff.lnk=#workers.staff)
		AND CONVERT(DATETIME, CASE WHEN LEN(RTRIM(Q.DATE_BEGIN))=10 THEN Q.DATE_BEGIN ELSE NULL END,104) BETWEEN @dDateH1 AND @dDateH2
		AND DEP.LINK=isnull(dbo.BK_getDepZB(), dbo.getowndeplink())
		AND Q.FACE=#WORKERS.FACE
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 7.00, '
	UPDATE #T_RES
	SET	S_26555 = (SELECT NAME FROM DICTIONARY_DEPARTMENT WHERE LINK=S_26550) /*Организация*/ FROM #T_RES T 
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 8.00, '
	UPDATE #T_RES
	SET	S_26565 = (SELECT P.FM FROM PERSON P WHERE P.LINK=(SELECT PERS_LINK FROM EMPL WHERE LINK = S_26560)) /*Фамилия*/ FROM #T_RES T 
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 9.00, '
	UPDATE #T_RES
	SET	S_26569 = (SELECT P.IM FROM PERSON P  WHERE P.LINK=(SELECT PERS_LINK FROM EMPL WHERE LINK = S_26560)) /*Имя*/ FROM #T_RES T 
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 1.00, 'CREATE PROCEDURE #P_SQUERY
		@dDate_1 DATETIME /*Дата формирования*/,
		@dDateH1 DATETIME /*Событие - начало периода*/,
		@dDateH2 DATETIME /*Событие - конец периода*/,
		@nCheck_1 INT /*Выводить итоги*/,
		@varKScTableInto varchar(20) = ''''
AS
BEGIN

	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 2.00, '
	CREATE TABLE  #WORKERS (FACE INT, START_DATE DATETIME, END_DATE DATETIME, STAFF INT,  LINK_DEP INT)
EXEC K_FILL_T_WORKERS @dDate_1

', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 18.00, '
	UPDATE #T_RES
	SET	S_91913 = (SELECT ( rtrim(P.FM) +'' '' +rtrim(P.IM)+'' ''+ rtrim(P.OT)+'' ''  ) FROM PERSON P WHERE P.LINK=(SELECT PERS_LINK FROM EMPL WHERE LINK = S_26560)) /*ФИО*/ FROM #T_RES T  
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 20.00, '	
SELECT * FROM #T_RES2 

', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 21.00, '
	DROP TABLE #T_RES
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 22.00, '
	DROP TABLE #WORKERS

	DROP TABLE #QUALIFY

	DROP TABLE #STAFF

	SET TRANSACTION ISOLATION LEVEL READ COMMITTED

END', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 16.00, '
	UPDATE #T_RES
	SET	S_87614 = (SELECT PROG_NAME FROM #QUALIFY WHERE ID = S_26579) /*Наименование курса*/ FROM #T_RES T 
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 17.00, '
	UPDATE #T_RES
	SET	S_91903 = (SELECT [TIME] FROM #QUALIFY WHERE ID = S_26579) /*Количество часов обучения*/ FROM #T_RES T 
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 19.00, '
	SELECT 
		S_26555 AS S_26555 /*Организация*/,
		S_26598 AS S_26598 /*Вид повышения квалификации*/,
		S_26615 AS S_26615 /*Подразделение - порядок*/,
		S_26565 AS S_26565 /*Фамилия*/,
		S_26569 AS S_26569 /*Имя*/,
		S_26573 AS S_26573 /*Отчество*/,
		S_26628 AS S_26628 /*Должность*/,
		S_26584 AS S_26584 /*Дата начала обучения*/,
		S_26588 AS S_26588 /*Дата окончания обучения*/,
		S_26594 AS S_26594 /*Номер документа*/,
		S_26607 AS S_26607 /*Подразделение*/,
		S_26560 AS S_26560 /*Лицо*/,
		S_87614 AS S_87614 /*Наименование курса*/,
		S_26611 AS S_26611 /*Подразделение - код*/,
		S_26619 AS S_26619 /*Подразделение - уровень*/,
		S_27669 AS S_27669 /*Наименование образовательного учреждения*/,
		S_26550 AS S_26550 /*Организация - ключ*/,
		S_26579 AS S_26579 /*Повышение квалификации - запись*/,
		S_26602 AS S_26602 /*Запись штатного расписания*/,
		S_91903 AS S_91903 /*Количество часов обучения*/,
		S_91913 AS S_91913 /*ФИО*/
		
	INTO #T_RES2
	FROM #T_RES T
	GROUP BY  S_26555, S_26565, S_26569, S_26573, S_91913, S_26584, S_26598, S_87614, S_26628, S_26615, S_26588, S_26594, S_26607, S_26560, S_26611, S_26619, S_27669, S_26550, S_26579, S_26602, S_91903

', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 10.00, '
	UPDATE #T_RES
	SET	S_26573 = (SELECT P.OT FROM PERSON P  WHERE P.LINK=(SELECT PERS_LINK FROM EMPL WHERE LINK = S_26560)) /*Отчество*/ FROM #T_RES T 
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 11.00, '
	UPDATE #T_RES
	SET	S_26584 = CONVERT( DATETIME, (SELECT DATE_BEGIN FROM  #QUALIFY WHERE ID=S_26579 ), 104) /*Дата начала обучения*/ FROM #T_RES T 
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 12.00, '
	UPDATE #T_RES
	SET	S_26588 = CONVERT( DATETIME, (SELECT DATE_END FROM  #QUALIFY WHERE ID=S_26579 ), 104) /*Дата окончания обучения*/ FROM #T_RES T 
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 3.00, '
	CREATE TABLE #QUALIFY
(
	ID INT IDENTITY,
	FACE INT, 
	DATE_BEGIN VARCHAR(10),
	DATE_END	VARCHAR(10),
	LINK_TYPE INT,
	TYPE VARCHAR(254),
	DOC_NAME VARCHAR(254),
	DOC_SERNUM VARCHAR(254),
	DOC_DATE VARCHAR(10),
	REASON VARCHAR(254),
	PLACE VARCHAR(254),
	NUMBER INT,
	PLACE_LINK INT,
	PLACE_CODE VARCHAR(5),
	FIN_LINK INT,
	FIN_SRC VARCHAR(254),
	FIN_CODE VARCHAR(2),
	NAPR_LINK INT,
	NAPR VARCHAR(100),
	NAPR_CODE VARCHAR(2),
	PROG_NAME VARCHAR(500),
	TIME INT
)

EXEC K_FILL_T_QUALIFY

', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 4.00, '
	CREATE TABLE #STAFF 
( 
	num_otd INT, 
	LNK INT,
	LINK_OTD INT,
	SUBDIV_CODE VARCHAR(5),
	SUBDIV_NAME VARCHAR(254), 
	LINK_DOL INT,  
	POST_CODE VARCHAR(6),
	POST_NAME VARCHAR(254), 
	NORM  NUMERIC(20,2),
	FACT NUMERIC(20,2),  
	VAC  NUMERIC(20,2), 
	OKLAD NUMERIC(20,2), 
	FOT NUMERIC(20,2), 
	LEVEL_OTD INT, 
	CHIN_LINK INT,
	CHIN_CODE VARCHAR(10),
	CHIN VARCHAR(254),
	CONFIRMED NUMERIC(20,2),
	DEYAT_TYPE_LINK INT,
	DEYAT_TYPE VARCHAR(80),
	KATEG_LINK INT,
	KATEG_CODE VARCHAR(3),
	KATEG_DOL VARCHAR(40),
	GOSSL BIT,
	FEDERAL BIT, 
	FOND BIT,
	LINK_DEP INT, 
	LINK_PARENT INT, 
	NUM_PARENT INT,
	KAT_GOS_LINK INT,
	KAT_GOS_CODE VARCHAR(3),
	KAT_GOS_NAME VARCHAR(254),
	GR_GOS_LINK INT,
	GR_GOS_CODE VARCHAR(3),
	GR_GOS_NAME VARCHAR(254)
)


EXEC K_FILL_T_STAFF


', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 13.00, '
	UPDATE #T_RES
	SET	S_27669 = (SELECT PLACE FROM  #QUALIFY WHERE ID=S_26579 ) /*Наименование образовательного учреждения*/ FROM #T_RES T 
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 176.00, NULL, 14.00, '
	UPDATE #T_RES
	SET	S_26594 = (SELECT DOC_SERNUM FROM  #QUALIFY WHERE ID=S_26579 ) /*Номер документа*/ FROM #T_RES T 
', 'SYS_POV_KVALIF', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6711.00, 347.00, NULL, NULL, 'REPMAKERSTANDARD.BAS', 'SYS_POV_KVALIF', 'QUERY_ADD_MODULE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6712.00, 139.00, NULL, NULL, 'S_26550', 'SYS_POV_KVALIF_LINK_DEP', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6712.00, 148.00, NULL, NULL, '0', 'SYS_POV_KVALIF_LINK_DEP', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6712.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_DEP', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6716.00, 139.00, NULL, NULL, 'S_26555', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6716.00, 140.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6716.00, 141.00, NULL, NULL, '', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SQUERY_FIELD_FORMAT_C_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6716.00, 144.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SQUERY_FIELD_GROUP_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6716.00, 146.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SQUERY_FIELD_HIDE_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6716.00, 148.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6716.00, 153.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SQUERY_FIELD_SUBTOTAL_CHECK')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6716.00, 154.00, NULL, NULL, 'Итого по *', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SQUERY_FIELD_SUBTOTAL_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6716.00, 155.00, NULL, NULL, '3', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6716.00, 156.00, NULL, NULL, '40', 'SYS_POV_KVALIF_LINK_DEP_DEP', 'SQUERY_FIELD_WIDTH_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6721.00, 139.00, NULL, NULL, 'S_26560', 'SYS_POV_KVALIF_LINK_FACE', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6721.00, 140.00, NULL, NULL, '0', 'SYS_POV_KVALIF_LINK_FACE', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6721.00, 147.00, NULL, NULL, '', 'SYS_POV_KVALIF_LINK_FACE', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6721.00, 148.00, NULL, NULL, '0', 'SYS_POV_KVALIF_LINK_FACE', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6721.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_FACE', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6739.00, 139.00, NULL, NULL, 'S_26579', 'SYS_POV_KVALIF_LINK_KVAL', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6739.00, 148.00, NULL, NULL, '0', 'SYS_POV_KVALIF_LINK_KVAL', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6739.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_KVAL', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6743.00, 139.00, NULL, NULL, 'S_26584', 'SYS_POV_KVALIF_KVAL_D1', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6743.00, 140.00, NULL, NULL, '3', 'SYS_POV_KVALIF_KVAL_D1', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6743.00, 142.00, NULL, NULL, 'ДД.ММ.ГГГГ', 'SYS_POV_KVALIF_KVAL_D1', 'SQUERY_FIELD_FORMAT_D_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6743.00, 148.00, NULL, NULL, '6', 'SYS_POV_KVALIF_KVAL_D1', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6743.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_KVAL_D1', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6743.00, 156.00, NULL, NULL, '15', 'SYS_POV_KVALIF_KVAL_D1', 'SQUERY_FIELD_WIDTH_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6747.00, 139.00, NULL, NULL, 'S_26588', 'SYS_POV_KVALIF_KVAL_D2', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6747.00, 140.00, NULL, NULL, '3', 'SYS_POV_KVALIF_KVAL_D2', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6747.00, 141.00, NULL, NULL, '', 'SYS_POV_KVALIF_KVAL_D2', 'SQUERY_FIELD_FORMAT_C_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6747.00, 142.00, NULL, NULL, 'ДД.ММ.ГГГГ', 'SYS_POV_KVALIF_KVAL_D2', 'SQUERY_FIELD_FORMAT_D_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6747.00, 148.00, NULL, NULL, '7', 'SYS_POV_KVALIF_KVAL_D2', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6747.00, 155.00, NULL, NULL, '3', 'SYS_POV_KVALIF_KVAL_D2', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6747.00, 156.00, NULL, NULL, '15', 'SYS_POV_KVALIF_KVAL_D2', 'SQUERY_FIELD_WIDTH_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6753.00, 139.00, NULL, NULL, 'S_26594', 'SYS_POV_KVALIF_KVAL_DOC', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6753.00, 140.00, NULL, NULL, '3', 'SYS_POV_KVALIF_KVAL_DOC', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6753.00, 141.00, NULL, NULL, '', 'SYS_POV_KVALIF_KVAL_DOC', 'SQUERY_FIELD_FORMAT_C_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6753.00, 148.00, NULL, NULL, '12', 'SYS_POV_KVALIF_KVAL_DOC', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6753.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_KVAL_DOC', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6753.00, 156.00, NULL, NULL, '20', 'SYS_POV_KVALIF_KVAL_DOC', 'SQUERY_FIELD_WIDTH_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6757.00, 139.00, NULL, NULL, 'S_26598', 'SYS_POV_KVALIF_KVAL_TYPE', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6757.00, 140.00, NULL, NULL, '3', 'SYS_POV_KVALIF_KVAL_TYPE', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6757.00, 141.00, NULL, NULL, '', 'SYS_POV_KVALIF_KVAL_TYPE', 'SQUERY_FIELD_FORMAT_C_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6757.00, 148.00, NULL, NULL, '10', 'SYS_POV_KVALIF_KVAL_TYPE', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6757.00, 153.00, NULL, NULL, '0', 'SYS_POV_KVALIF_KVAL_TYPE', 'SQUERY_FIELD_SUBTOTAL_CHECK')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6757.00, 154.00, NULL, NULL, 'Итого по виду:*', 'SYS_POV_KVALIF_KVAL_TYPE', 'SQUERY_FIELD_SUBTOTAL_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6757.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_KVAL_TYPE', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6757.00, 156.00, NULL, NULL, '40', 'SYS_POV_KVALIF_KVAL_TYPE', 'SQUERY_FIELD_WIDTH_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6761.00, 139.00, NULL, NULL, 'S_26602', 'SYS_POV_KVALIF_LINK_STAFF', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6761.00, 148.00, NULL, NULL, '0', 'SYS_POV_KVALIF_LINK_STAFF', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6761.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_STAFF', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6765.00, 139.00, NULL, NULL, 'S_26607', 'SYS_POV_KVALIF_STAFF_SUB', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6765.00, 140.00, NULL, NULL, '3', 'SYS_POV_KVALIF_STAFF_SUB', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6765.00, 141.00, NULL, NULL, '', 'SYS_POV_KVALIF_STAFF_SUB', 'SQUERY_FIELD_FORMAT_C_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6765.00, 145.00, NULL, NULL, '', 'SYS_POV_KVALIF_STAFF_SUB', 'SQUERY_FIELD_HEIGHT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6765.00, 148.00, NULL, NULL, '5', 'SYS_POV_KVALIF_STAFF_SUB', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6765.00, 151.00, NULL, NULL, '2', 'SYS_POV_KVALIF_STAFF_SUB', 'SQUERY_FIELD_SORT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6765.00, 153.00, NULL, NULL, '1', 'SYS_POV_KVALIF_STAFF_SUB', 'SQUERY_FIELD_SUBTOTAL_CHECK')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6765.00, 154.00, NULL, NULL, 'Итого по подразделению *', 'SYS_POV_KVALIF_STAFF_SUB', 'SQUERY_FIELD_SUBTOTAL_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6765.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_STAFF_SUB', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6765.00, 156.00, NULL, NULL, '40', 'SYS_POV_KVALIF_STAFF_SUB', 'SQUERY_FIELD_WIDTH_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6769.00, 139.00, NULL, NULL, 'S_26611', 'SYS_POV_KVALIF_STAFF_SBC', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6769.00, 148.00, NULL, NULL, '5', 'SYS_POV_KVALIF_STAFF_SBC', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6769.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_STAFF_SBC', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6773.00, 139.00, NULL, NULL, 'S_26615', 'SYS_POV_KVALIF_STAFF_ORD', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6773.00, 140.00, NULL, NULL, '3', 'SYS_POV_KVALIF_STAFF_ORD', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6773.00, 143.00, NULL, NULL, '1', 'SYS_POV_KVALIF_STAFF_ORD', 'SQUERY_FIELD_FORMULA_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6773.00, 146.00, NULL, NULL, '1', 'SYS_POV_KVALIF_STAFF_ORD', 'SQUERY_FIELD_HIDE_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6773.00, 148.00, NULL, NULL, '5', 'SYS_POV_KVALIF_STAFF_ORD', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6773.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_STAFF_ORD', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6777.00, 139.00, NULL, NULL, 'S_26619', 'SYS_POV_KVALIF_STAFF_SBL', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6777.00, 148.00, NULL, NULL, '5', 'SYS_POV_KVALIF_STAFF_SBL', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6777.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_STAFF_SBL', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6781.00, 1.00, NULL, NULL, '0', 'SYS_POV_KVALIF_NASTR1', 'SQUERY_NASTR_OPTIONAL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6781.00, 163.00, NULL, NULL, '@dDate_1', 'SYS_POV_KVALIF_NASTR1', 'SQUERY_NASTR_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6781.00, 165.00, NULL, NULL, 'DATEBOX_WD', 'SYS_POV_KVALIF_NASTR1', 'SQUERY_NASTR_OBJECT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6781.00, 168.00, NULL, NULL, 'Текущая дата', 'SYS_POV_KVALIF_NASTR1', 'SQUERY_NASTR_VALUE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6782.00, 1.00, NULL, NULL, '0', 'SYS_POV_KVALIF_NASTR2', 'SQUERY_NASTR_OPTIONAL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6782.00, 163.00, NULL, NULL, '@dDateH1', 'SYS_POV_KVALIF_NASTR2', 'SQUERY_NASTR_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6782.00, 165.00, NULL, NULL, 'DATEBOX_PB', 'SYS_POV_KVALIF_NASTR2', 'SQUERY_NASTR_OBJECT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6782.00, 168.00, NULL, NULL, 'Начало года', 'SYS_POV_KVALIF_NASTR2', 'SQUERY_NASTR_VALUE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6783.00, 1.00, NULL, NULL, '0', 'SYS_POV_KVALIF_NASTR3', 'SQUERY_NASTR_OPTIONAL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6783.00, 163.00, NULL, NULL, '@dDateH2', 'SYS_POV_KVALIF_NASTR3', 'SQUERY_NASTR_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6783.00, 165.00, NULL, NULL, 'DATEBOX_PE', 'SYS_POV_KVALIF_NASTR3', 'SQUERY_NASTR_OBJECT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6783.00, 168.00, NULL, NULL, 'Конец года', 'SYS_POV_KVALIF_NASTR3', 'SQUERY_NASTR_VALUE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6784.00, 139.00, NULL, NULL, 'S_26628', 'SYS_POV_KVALIF_STAFF_POST', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6784.00, 140.00, NULL, NULL, '3', 'SYS_POV_KVALIF_STAFF_POST', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6784.00, 142.00, NULL, NULL, '@', 'SYS_POV_KVALIF_STAFF_POST', 'SQUERY_FIELD_FORMAT_D_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6784.00, 148.00, NULL, NULL, '4', 'SYS_POV_KVALIF_STAFF_POST', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6784.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_STAFF_POST', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6784.00, 156.00, NULL, NULL, '30', 'SYS_POV_KVALIF_STAFF_POST', 'SQUERY_FIELD_WIDTH_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (17853.00, 139.00, NULL, NULL, 'S_87614', '041FFD3C-1026-42B9-9E05-30D01A872C6C', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (17853.00, 140.00, NULL, NULL, '3', '041FFD3C-1026-42B9-9E05-30D01A872C6C', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (17853.00, 141.00, NULL, NULL, '', '041FFD3C-1026-42B9-9E05-30D01A872C6C', 'SQUERY_FIELD_FORMAT_C_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (17853.00, 148.00, NULL, NULL, '9', '041FFD3C-1026-42B9-9E05-30D01A872C6C', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (17853.00, 155.00, NULL, NULL, '1', '041FFD3C-1026-42B9-9E05-30D01A872C6C', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (17853.00, 156.00, NULL, NULL, '40', '041FFD3C-1026-42B9-9E05-30D01A872C6C', 'SQUERY_FIELD_WIDTH_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19552.00, 139.00, NULL, NULL, 'S_91903', 'SYS_POV_KVALIF_KVAL_QH', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19552.00, 140.00, NULL, NULL, '3', 'SYS_POV_KVALIF_KVAL_QH', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19552.00, 141.00, NULL, NULL, '', 'SYS_POV_KVALIF_KVAL_QH', 'SQUERY_FIELD_FORMAT_C_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19552.00, 142.00, NULL, NULL, '# ##0,00', 'SYS_POV_KVALIF_KVAL_QH', 'SQUERY_FIELD_FORMAT_D_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19552.00, 143.00, NULL, NULL, '1', 'SYS_POV_KVALIF_KVAL_QH', 'SQUERY_FIELD_FORMULA_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19552.00, 144.00, NULL, NULL, '1', 'SYS_POV_KVALIF_KVAL_QH', 'SQUERY_FIELD_GROUP_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19552.00, 147.00, NULL, NULL, '', 'SYS_POV_KVALIF_KVAL_QH', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19552.00, 148.00, NULL, NULL, '11', 'SYS_POV_KVALIF_KVAL_QH', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19552.00, 155.00, NULL, NULL, '1', 'SYS_POV_KVALIF_KVAL_QH', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19552.00, 156.00, NULL, NULL, '10', 'SYS_POV_KVALIF_KVAL_QH', 'SQUERY_FIELD_WIDTH_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19553.00, 139.00, NULL, NULL, 'S_91913', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19553.00, 140.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19553.00, 141.00, NULL, NULL, '', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SQUERY_FIELD_FORMAT_C_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19553.00, 144.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SQUERY_FIELD_GROUP_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19553.00, 148.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19553.00, 151.00, NULL, NULL, '2', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SQUERY_FIELD_SORT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19553.00, 153.00, NULL, NULL, '1', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SQUERY_FIELD_SUBTOTAL_CHECK')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19553.00, 154.00, NULL, NULL, 'Итого по сотруднику *', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SQUERY_FIELD_SUBTOTAL_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19553.00, 155.00, NULL, NULL, '3', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (19553.00, 156.00, NULL, NULL, '40', 'SYS_POV_KVALIF_LINK_FACE_FIO', 'SQUERY_FIELD_WIDTH_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (20321.00, 1.00, NULL, NULL, '1', 'SYS_POV_KVALIF_NASTR4', 'SQUERY_NASTR_OPTIONAL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (20321.00, 163.00, NULL, NULL, '@nCheck_1', 'SYS_POV_KVALIF_NASTR4', 'SQUERY_NASTR_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (20321.00, 165.00, NULL, NULL, 'CHECKBOX', 'SYS_POV_KVALIF_NASTR4', 'SQUERY_NASTR_OBJECT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (20321.00, 166.00, NULL, NULL, '1', 'SYS_POV_KVALIF_NASTR4', 'SQUERY_NASTR_SAVE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (20321.00, 168.00, NULL, NULL, 'Вкл.', 'SYS_POV_KVALIF_NASTR4', 'SQUERY_NASTR_VALUE')

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', 'Повышение квалификации', -4.00, 1, 'KADRY_FREE_PROF_REFR', 'SQUERY_USER', 'SYS_POV_KVALIF', 'REPORT_QUERY')

GO

		exec KIR_UPGRADE_OV 0 
GO

		DROP TABLE #T_OV
GO

		DROP TABLE #T_OVV
GO

		DROP TABLE #T_NAVIGATOR
GO


GO
